效果图:
XML 文件:
创建一个点击按钮并添加点击方法:<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="showAlertDialog"
android:text="alertDialog" />
</LinearLayout>
MainActivity:实现点击按钮的监听方法
public void showAlertDialog(View view){
/*
* 设置单选items
* */
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);//内部使用构建者的设计模式
final String[] items = {"苹果","橘子","香蕉"};
builder.setTitle("Dialog");
builder.setSingleChoiceItems(items, -1,new OnClickListener() {//第二个参数是设置默认选中哪一项-1代表默认都不选
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, items[which], 0).show();
}
});
builder.setCancelable(false);//设置dialog只能通过点击Dialog上的按钮退出,不能通过回退按钮退出关闭Dialog
builder.create().show();//创建对象
}