实现不选择选项则不可以关闭的对话框之方法一

本方法中,当点击Positive Button时,如果没有选择选项,则会以Toast的方式给出提示。

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
	private Button btnOpenDialog;
	private String[] books = null;
	private Activity activity;
	private int selectedBookIndex = -1;
	private AlertDialog alertDialog;
	private boolean allowCloseDialog = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initBooks();
		setContentView(R.layout.activity_main);
		activity = this;
		btnOpenDialog = (Button) findViewById(R.id.btnOpenDialog);
		btnOpenDialog.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				alertDialog = new AlertDialog.Builder(activity).setTitle(R.string.hello_world).setSingleChoiceItems(books, selectedBookIndex, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						selectedBookIndex = which;
						allowCloseDialog = true;
					}

				}).setPositiveButton("OK", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				}).create();
				
				alertDialog.show();
				alertDialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						if (allowCloseDialog) {
							alertDialog.dismiss();
						} else {
							Toast.makeText(activity, "Please select one option first.", Toast.LENGTH_LONG).show();
						}
					}
				});

			}
		});
	}

	void initBooks() {
		books = new String[] { "飞狐外传", "雪山飞狐", "连城诀", "天龙八部", "射雕英雄传", "白马啸西风", "鹿鼎记", "笑傲江湖", "书剑恩仇录", "神雕侠侣", "侠客行", "倚天屠龙记", "碧血剑", "鸳鸯刀", "越女剑" };
	}
}

相关推荐