AlertDialog 对话框 二或三选择项

来源:互联网 发布:knockout.js pdf 编辑:程序博客网 时间:2024/05/21 09:03

通过添加AlertDialog,我们可以在当前页面弹出一个对话框,它是在所有其他控件之前的,可以屏蔽其他控件的交互,并为用户提供选择。如果只需要两个选择(是或否),为AlertDialog添加setPositiveButton()方法和setNegativeButton()方法以及它们的点击事件即可,需要第三个选择时可以添加一个setNeutralButton()方法(三个按钮的位置请看本文最后的运行结果)。setCancelable(false),括号里设置为false,按退出键不能退出,这个地方默认为true。最后不要忘记:需要show()方法使对话框显现出来。代码如下:
(1)Java部分:

package com.example.alertdialog;import android.app.Activity;import android.app.AlertDialog;import android.content.DialogInterface;import android.os.Bundle;import android.view.View;import android.view.Window;public class MainActivity extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        requestWindowFeature(Window.FEATURE_NO_TITLE);        setContentView(R.layout.activity_main);    }  public void myclick(View v){      AlertDialog.Builder dialog = new AlertDialog.              Builder(MainActivity.this);      dialog.setTitle("对话框");//对话框最上面的字      dialog.setMessage("重要的事");//对话框中部的字      dialog.setCancelable(false);//这里设置为false,按退出键不能退出,这个地方默认为true//以下为对话框最下面的选择项      dialog.setPositiveButton("右边", new DialogInterface.              OnClickListener() {          @Override        public void onClick(DialogInterface dialog, int which) {        }    });      dialog.setNegativeButton("左边", new DialogInterface.              OnClickListener() {          @Override        public void onClick(DialogInterface dialog, int which) {        }    });      /*       * 需要第三个按钮时,才添加如下的setNeutralButton()       */      dialog.setNeutralButton("中间", new DialogInterface.              OnClickListener() {          @Override        public void onClick(DialogInterface dialog, int which) {        }    });      dialog.show();    }}

(2)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"     >    <Button         android:text="AlertDialog"        android:layout_gravity="center"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:onClick="myclick"        /></LinearLayout>

(3)运行结果:

这里写图片描述

1 0
原创粉丝点击