8种android 对话框(Dialog)使用方法详解

2019-12-10 18:51:14王振洲
易采站长站为您分析8种android 对话框(Dialog)使用方法。感兴趣的朋友可以参考一下  

本文汇总了android 8种对话框(Dialog)使用方法,,具体内容如下

1.写在前面

Android提供了丰富的Dialog函数,本文介绍最常用的8种对话框的使用方法,包括普通(包含提示消息和按钮)、列表、单选、多选、等待、进度条、编辑、自定义等多种形式,将在第2部分介绍。
有时,我们希望在对话框创建或关闭时完成一些特定的功能,这需要复写Dialog的create()、show()、dismiss()等方法,将在第3部分介绍。

2.代码示例

2.1 普通Dialog(图1与图2)

2个按钮

public class MainActivity extends Activity {
 
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button buttonNormal = (Button) findViewById(R.id.button_normal);
    buttonNormal.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        showNormalDialog();
      }
    });
  }
   
  private void showNormalDialog(){
    /* @setIcon 设置对话框图标
     * @setTitle 设置对话框标题
     * @setMessage 设置对话框消息提示
     * setXXX方法返回Dialog对象,因此可以链式设置属性
     */
    final AlertDialog.Builder normalDialog = 
      new AlertDialog.Builder(MainActivity.this);
    normalDialog.setIcon(R.drawable.icon_dialog);
    normalDialog.setTitle("我是一个普通Dialog")
    normalDialog.setMessage("你要点击哪一个按钮呢?");
    normalDialog.setPositiveButton("确定", 
      new DialogInterface.OnClickListener() {
      @Override
      public void onClick(DialogInterface dialog, int which) {
        //...To-do
      }
    });
    normalDialog.setNegativeButton("关闭", 
      new DialogInterface.OnClickListener() {
      @Override
      public void onClick(DialogInterface dialog, int which) {
        //...To-do
      }
    });
    // 显示
    normalDialog.show();
  }
}

3个按钮

/* @setNeutralButton 设置中间的按钮
 * 若只需一个按钮,仅设置 setPositiveButton 即可
 */
private void showMultiBtnDialog(){
  AlertDialog.Builder normalDialog = 
    new AlertDialog.Builder(MainActivity.this);
  normalDialog.setIcon(R.drawable.icon_dialog);
  normalDialog.setTitle("我是一个普通Dialog").setMessage("你要点击哪一个按钮呢?");
  normalDialog.setPositiveButton("按钮1", 
    new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
      // ...To-do
    }
  });
  normalDialog.setNeutralButton("按钮2", 
    new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
      // ...To-do
    }
  });
  normalDialog.setNegativeButton("按钮3", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
      // ...To-do
    }
  });
  // 创建实例并显示
  normalDialog.show();
}