开发对话框Dialog的学习资料和dialog选中位置的问题

Android提供了丰富的Dialog函数,本文介绍最常用的8种对话框的使用方法,包括普通(包含提示消息和按钮)、列表、单选、多选、等待、进度条、编辑、自定义等多种形式。

1:普通Dialog

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("普通对话框")
        .setIcon(R.mipmap.ic_launcher)
        .setMessage("你要点击的是哪个按键?")
        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                startActivity(intent);
                showToast("确定");

            }
        })
        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                showToast("取消");
            }
        })
        .show();


2:列表Dialog

final String[] mList = {"选项1", "选项2", "选项3", "选项4", "选项5", "选项6", "选项7"};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("列表对话框")
        .setIcon(R.mipmap.ic_launcher)
        .setItems(mList, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                showToast(mList[which]);
            }
        })
        .show();

3:单选Dialog

final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
final String[] sex = {"男", "女", "性别未定"};

builder.setTitle("单选对话框")
        .setIcon(R.mipmap.ic_launcher)
        .setSingleChoiceItems(sex, 0, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                chooseWhich = which;
                SharedPreferences sharedPreferences = getSharedPreferences("data", MODE_PRIVATE);
                SharedPreferences.Editor edit = sharedPreferences.edit();
                edit.putString("sex", sex[chooseWhich]);
                edit.apply();
                showToast(sex[chooseWhich]);
            }
        })
        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                chooseWhich = which;
                SharedPreferences sharedPreferences = getSharedPreferences("data", MODE_PRIVATE);
                String data = sharedPreferences.getString("sex", "");
                et_main.setText(data);


            }
        })

        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                showToast("取消");
            }
        })
        .show();

4:多选Dialog

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
final String[] mList = {"选项1", "选项2", "选项3", "选项4", "选项5", "选项6", "选项7"};
final boolean[] mLch = {false, false, false, false, false, false, false,};
builder.setTitle("多选对话框")
        .setIcon(R.mipmap.ic_launcher)
        .setMultiChoiceItems(mList, mLch, new DialogInterface.OnMultiChoiceClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                if (isChecked) {
                    yourChoices.add(which);

                } else {
                    yourChoices.remove(which);
                }
            }
        })
        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                int size = yourChoices.size();
                String str = "";
                for (int i = 0; i < size; i++) {
                    str += mList[yourChoices.get(i)];
                }

                showToast(str);

            }
        })
        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                showToast("取消");
            }
        })
        .show();

5:等待Dialog

final ProgressDialog dialog = new ProgressDialog(MainActivity.this);
dialog.setTitle("等待对话框");
dialog.setCancelable(false);
dialog.setMessage("等待中。。。。");
dialog.setIndeterminate(false);
dialog.show();
new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        dialog.dismiss();
    }
}).start();

6:进度条Dialog

final ProgressDialog dialog = new ProgressDialog(MainActivity.this);

dialog.setTitle("进度条话框");
dialog.setProgress(0);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMax(100);
dialog.show();
new Thread(new Runnable() {
    @Override
    public void run() {
        int progress = 0;
        while (progress < 100) {
            try {
                Thread.sleep(100);
                progress++;
                dialog.setProgress(progress);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
        dialog.cancel();
    }
}).start();


7:编辑Dialog

final EditText editText = new EditText(this);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("编辑对话框");
builder.setView(editText);
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        String s= editText.getText().toString();
        et_main.setText(s);
        showToast(s);
    }
});
builder.show();

8:自定义Dialog

final View view = View.inflate(MainActivity.this, R.layout.custom, null);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("编辑对话框");
builder.setView(view);
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
  EditText user= (EditText) view.findViewById(R.id.et_user);
  EditText password= (EditText) view.findViewById(R.id.et_password);
     String s=   user.getText().toString();
     String p=   password.getText().toString();
        et_main.setText(s+p);
    }
});
builder.show();
WindowManager m = getWindowManager();
Display d = m.getDefaultDisplay();  //为获取屏幕宽、高
WindowManager.LayoutParams p = dialog.getWindow().getAttributes();  //获取对话框当前的参数值
p.height = (int) (d.getHeight() * 0.5);   //高度设置为屏幕的0.5
p.width = (int) (d.getWidth() * 0.5);    //宽度设置为屏幕的0.5
dialog.getWindow().setAttributes(p);
编辑dialog的框高。


9:popupWindowDialog

final View view = View.inflate(MainActivity.this, R.layout.custom, null);
EditText user= (EditText) view.findViewById(R.id.et_user);
EditText password= (EditText) view.findViewById(R.id.et_password);
PopupWindow window   =new PopupWindow(view, ActionBarOverlayLayout.LayoutParams.WRAP_CONTENT, ActionBarOverlayLayout.LayoutParams.WRAP_CONTENT);
window.setFocusable(true);
window.setOutsideTouchable(true);
window.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
window.showAtLocation(view, Gravity.CENTER_VERTICAL,0,0);
10:MainActivity.java代码

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button btn_normal1;
    private Button btn_normal2;
    private Button btn_list;
    private Button btn_choose;
    private Button btn_multi_choose;
    private Button btn_wait;
    private Button btn_progress;
    private Button btn_editor;
    private Button btn_custom;
    private Button btn_pop;
    private EditText et_main;
    private int chooseWhich = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setView();
        setListener();
    }

    private void setListener() {
        btn_normal1.setOnClickListener(this);
        btn_normal2.setOnClickListener(this);
        btn_list.setOnClickListener(this);
        btn_choose.setOnClickListener(this);
        btn_multi_choose.setOnClickListener(this);
        btn_wait.setOnClickListener(this);
        btn_progress.setOnClickListener(this);
        btn_editor.setOnClickListener(this);
        btn_custom.setOnClickListener(this);
        btn_pop.setOnClickListener(this);
    }

    private void setView() {
        btn_normal1 = (Button) findViewById(R.id.btn_normal1);
        btn_normal2 = (Button) findViewById(R.id.btn_normal2);
        btn_list = (Button) findViewById(R.id.btn_list);
        btn_choose = (Button) findViewById(R.id.btn_choose);
        btn_multi_choose = (Button) findViewById(R.id.btn_multi_choose);
        btn_wait = (Button) findViewById(R.id.btn_wait);
        btn_progress = (Button) findViewById(R.id.btn_progress);
        btn_editor = (Button) findViewById(R.id.btn_editor);
        btn_custom = (Button) findViewById(R.id.btn_custom);
        btn_pop = (Button) findViewById(R.id.btn_pop);
        et_main = (EditText) findViewById(R.id.et_main);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_normal1:
                showNormalDialog1();
                break;
            case R.id.btn_normal2:
                showNormalDialog2();
                break;
            case R.id.btn_list:
                showListDialog();
                break;
            case R.id.btn_choose://实验保存选中位置

//重点问题:dialog重复创建,选中的位置保存无效。
原因:每次点击时候,这要操作都会重复创建Alertdialog对象。
解决方法:首先在[单选]按键定义一个int类型参数保存选中的whitch,
再次在[确认]按键用SharedPreference
保存选中的whitch,重点是要用builder,create()
创建dialog对象,再用dialog去show();







                //showChooseDialog();
if(dialog!=null){dialog.show();}else{dialog=bulider.create();dialog.show();}
                break;
            case R.id.btn_multi_choose:
                showMultiChooseDialog();
                break;
            case R.id.btn_wait:
                showPWaitDialog();
                break;
            case R.id.btn_progress:
                showProgressDialog();
                break;
            case R.id.btn_editor:
                showEditorDialog();
                break;
            case R.id.btn_custom:
                showCustomDialog();
                break;
            case R.id.btn_pop:
                shoePopDialog();
                break;
        }
    }
//popUpWindow
    private void shoePopDialog() {
        final View view = View.inflate(MainActivity.this, R.layout.custom, null);
        EditText user= (EditText) view.findViewById(R.id.et_user);
        EditText password= (EditText) view.findViewById(R.id.et_password);
        PopupWindow window   =new PopupWindow(view, ActionBarOverlayLayout.LayoutParams.WRAP_CONTENT, ActionBarOverlayLayout.LayoutParams.WRAP_CONTENT);
        window.setFocusable(true);
        window.setOutsideTouchable(true);
        window.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
        window.showAtLocation(view, Gravity.CENTER_VERTICAL,0,0);
    }

    //自定义对话框
    private void showCustomDialog() {
        final View view = View.inflate(MainActivity.this, R.layout.custom, null);
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("编辑对话框");
        builder.setView(view);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
          EditText user= (EditText) view.findViewById(R.id.et_user);
          EditText password= (EditText) view.findViewById(R.id.et_password);
             String s=   user.getText().toString();
             String p=   password.getText().toString();
                et_main.setText(s+p);
            }
        });
        builder.show();
    }



    //编辑对话框
    private void showEditorDialog() {
        final EditText editText = new EditText(this);
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("编辑对话框");
        builder.setView(editText);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String s= editText.getText().toString();
                et_main.setText(s);
                showToast(s);
            }
        });
        builder.show();
    }

    //进度条对话框
    private void showProgressDialog() {
        final ProgressDialog dialog = new ProgressDialog(MainActivity.this);

        dialog.setTitle("进度条话框");
        dialog.setProgress(0);
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setMax(100);
        dialog.show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                int progress = 0;
                while (progress < 100) {
                    try {
                        Thread.sleep(100);
                        progress++;
                        dialog.setProgress(progress);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
                dialog.cancel();
            }
        }).start();

    }

    //等待对话框
    private void showPWaitDialog() {
        final ProgressDialog dialog = new ProgressDialog(MainActivity.this);
        dialog.setTitle("等待对话框");
        dialog.setCancelable(false);
        dialog.setMessage("等待中。。。。");
        dialog.setIndeterminate(false);
        dialog.show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                dialog.dismiss();
            }
        }).start();
    }

    ArrayList<Integer> yourChoices = new ArrayList<>();

    //多选对话框
    private void showMultiChooseDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        final String[] mList = {"选项1", "选项2", "选项3", "选项4", "选项5", "选项6", "选项7"};
        final boolean[] mLch = {false, false, false, false, false, false, false,};
        builder.setTitle("多选对话框")
                .setIcon(R.mipmap.ic_launcher)
                .setMultiChoiceItems(mList, mLch, new DialogInterface.OnMultiChoiceClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                        if (isChecked) {
                            yourChoices.add(which);

                        } else {
                            yourChoices.remove(which);
                        }
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        int size = yourChoices.size();
                        String str = "";
                        for (int i = 0; i < size; i++) {
                            str += mList[yourChoices.get(i)];
                        }

                        showToast(str);

                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        showToast("取消");
                    }
                })
                .show();
    }

    //单选对话框
    private void showChooseDialog() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        final String[] sex = {"男", "女", "性别未定"};

        builder.setTitle("单选对话框")
                .setIcon(R.mipmap.ic_launcher)
                .setSingleChoiceItems(sex, 0, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        chooseWhich = which;
                        
                        showToast(sex[chooseWhich]);
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                       
                        SharedPreferences sharedPreferences = getSharedPreferences("data", MODE_PRIVATE);
                        SharedPreferences.Editor edit = sharedPreferences.edit();
                        edit.putString("sex", sex[chooseWhich]);
                        edit.putString("id", chooseWhich);
edit.apply() ; String data = sharedPreferences.getString( "sex" , "") ; et_main.setText(data) ; } }) .setNegativeButton( "取消" , new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog , int which) { showToast( "取消") ; } }) .show() ; } //列表对话框 private void showListDialog() { final String[] mList = { "选项1" , "选项2" , "选项3" , "选项4" , "选项5" , "选项6" , "选项7"} ; AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity. this) ; builder.setTitle( "列表对话框") .setIcon(R.mipmap. ic_launcher) .setItems(mList , new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog , int which) { showToast( mList[which]) ; } }) .show() ; } private void showNormalDialog2() { AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity. this) ; builder.setTitle( "普通对话框2") .setIcon(R.mipmap. ic_launcher) .setMessage( "你要点击的是哪个按键?") .setPositiveButton( "确定" , new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog , int which) { Intent intent = new Intent(MainActivity. this, SecondActivity. class) ; startActivity(intent) ; showToast( "确定") ; } }) .setNeutralButton( "忽略" , new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog , int which) { showToast( "忽略") ; } }) .setNegativeButton( "取消" , new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog , int which) { showToast( "取消") ; } }) .show() ; } //普通对话框1 private void showNormalDialog1() { AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity. this) ; builder.setTitle( "普通对话框") .setIcon(R.mipmap. ic_launcher) .setMessage( "你要点击的是哪个按键?") .setPositiveButton( "确定" , new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog , int which) { Intent intent = new Intent(MainActivity. this, SecondActivity. class) ; startActivity(intent) ; showToast( "确定") ; } }) .setNegativeButton( "取消" , new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog , int which) { showToast( "取消") ; } }) .show() ; } private void showToast(String msg) { Toast. makeText(MainActivity. this, "你点击的是+" + msg , Toast. LENGTH_SHORT).show() ; }}activi_main:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.jet.speech.dialogdemo.MainActivity">
<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <Button
        android:id="@+id/btn_normal1"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="普通Dialog1" />

    <Button
        android:id="@+id/btn_normal2"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="普通Dialog2" />
</LinearLayout>


    <Button
        android:id="@+id/btn_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="列表Dialog" />

    <Button
        android:id="@+id/btn_choose"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="单选Dialog" />

    <Button
        android:id="@+id/btn_multi_choose"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="多选Dialog" />

    <Button
        android:id="@+id/btn_wait"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="等待Dialog" />

    <Button
        android:id="@+id/btn_progress"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="进度条Dialog" />

    <Button
        android:id="@+id/btn_editor"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="编辑Dialog" />

    <Button
        android:id="@+id/btn_custom"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="自定义Dialog" />

    <Button
        android:id="@+id/btn_pop"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="PopUpWindowDialog" />

<EditText
    android:id="@+id/et_main"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />


</LinearLayout>

总结:对话框样式多,这只是简单的,要好好的弄,就要更多时间和精力。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值