在Android开发中,我们经常会需要在Android界面上弹出一些对话框,比如询问用户或者让用户选择。这些功能我们叫它Android Dialog对话框,AlertDialog实现方法为建造者模式。下面我们简单模拟一个选花魁的简单普通选项(单选)对话框,如下图:
images/loading.gif' data-original="http://images2015.cnblogs.com/blog/1068139/201611/1068139-20161124214715206-1632972485.gif" >
Layout界面代码:
1 <? 2 <LinearLayout 3 android:orientation="vertical" android:layout_width="match_parent" 4 android:layout_height="match_parent"> 5 <Button 6 android:text="普通选项" 7 android:layout_width="match_parent" 8 android:layout_height="wrap_content" 9 android:onClick="show2"10 android:id="@+id/button2" />11 </LinearLayout>
Java功能实现代码:
1 public class AlertDialogDemo extends AppCompatActivity { 2 @Override 3 protected void onCreate(@Nullable Bundle savedInstanceState) { 4 super.onCreate(savedInstanceState); 5 setContentView(R.layout.alertdialog); 6 } 7 public void show2(View v){ 8 //实例化建造者 9 AlertDialog.Builder builder = new AlertDialog.Builder(this);10 //设置警告对话框标题11 builder.setTitle("选花魁喽");12 //定义警告框选择窗体的内容(这里用String数组)13 final String[] beautifulGirls = {"芙蓉姐姐","凤姐","范爷","我自己"};14 //将数组内的元素设置到dialog的每个item中,并做事件处理(这里用土司)15 builder.setItems(beautifulGirls, new DialogInterface.OnClickListener() {16 @Override17 public void onClick(DialogInterface dialog, int which) {18 Toast.makeText(AlertDialogDemo.this,beautifulGirls[which]+"被选中啦",Toast.LENGTH_SHORT).show();19 }20 });21 //显示对话框22 builder.show();23 }24 }
原标题:Android中的AlertDialog使用示例二(普通选项对话框)
关键词:Android