实现不选择选项则不可以关闭的对话框之方法一
本方法中,当点击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[] { "飞狐外传", "雪山飞狐", "连城诀", "天龙八部", "射雕英雄传", "白马啸西风", "鹿鼎记", "笑傲江湖", "书剑恩仇录", "神雕侠侣", "侠客行", "倚天屠龙记", "碧血剑", "鸳鸯刀", "越女剑" }; } }
相关推荐
huha 2020-10-16
xfcyhades 2020-11-20
sgafdsg 2020-11-04
Michael 2020-11-03
fengyeezju 2020-10-14
ziyexiaoxiao 2020-10-14
业余架构师 2020-10-09
OuNuo0 2020-09-29
moses 2020-09-22
Angelia 2020-09-11
qinxu 2020-09-10
刘炳昭 2020-09-10
Nostalgiachild 2020-09-07
Nostalgiachild 2020-08-17
leavesC 2020-08-14
一青年 2020-08-13
AndroidAiStudy 2020-08-07
ydc0 2020-07-30
绿豆饼 2020-07-28