实现不选择选项则不可以关闭的对话框之方法二
import android.app.Activity;import android.app.AlertDialog;import android.app.Dialog;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;@Overrideprotected 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() {@Overridepublic void onClick(View v) {alertDialog = new AlertDialog.Builder(activity).setTitle(R.string.hello_world).setSingleChoiceItems(books, selectedBookIndex, new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {selectedBookIndex = which;allowCloseDialogByTapPositiveButton();}}).setNegativeButton("取消", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {selectedBookIndex = -1;// distoryDialog(dialog);return;}}).setPositiveButton("确定", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {if(selectedBookIndex == -1){alertDialog.getButton(Dialog.BUTTON_POSITIVE).setEnabled(false);Toast.makeText(activity, "对不起,你不买书,不能走购物通道啊!", Toast.LENGTH_LONG).show();// keepDialog(dialog);return;}else{Toast.makeText(activity, "您选择了图书:" + books[selectedBookIndex] + ".", Toast.LENGTH_LONG).show();}}}).show();alertDialog.setCancelable(false);alertDialog.setCanceledOnTouchOutside(false);allowCloseDialogByTapPositiveButton();}});}private void allowCloseDialogByTapPositiveButton() { if(selectedBookIndex > -1) {alertDialog.getButton(Dialog.BUTTON_POSITIVE).setEnabled(true);}else{alertDialog.getButton(Dialog.BUTTON_POSITIVE).setEnabled(false);} }void initBooks() {books = new String[] { "飞狐外传", "雪山飞狐", "连城诀", "天龙八部", "射雕英雄传", "白马啸西风", "鹿鼎记", "笑傲江湖", "书剑恩仇录", "神雕侠侣", "侠客行", "倚天屠龙记", "碧血剑", "鸳鸯刀", "越女剑" };}}
?