1. 程式人生 > >Android Dialog使用、自定義帶動畫的Dialog使用

Android Dialog使用、自定義帶動畫的Dialog使用

效果圖

這裡寫圖片描述

普通Dialog

private void showNormalDialog() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setIcon(R.mipmap.ic_launcher)
                .setTitle("普通Dialog")
                .setMessage("這是一個普通的Dialog")
                .setPositiveButton("確定"
, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }) .setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override
public void onClick(DialogInterface dialogInterface, int i) { } }) .show(); //新增中間按鈕 就有三個按鈕 //normalDialog.setNeutralButton }

列表Dialog

private void showListDialog() {
        final String[] items = {"按鈕1"
, "按鈕2", "按鈕3", "按鈕4"}; AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setTitle("列表Dialog") .setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }) .show(); }

單選Dialog

private void showSingleChoiceDialog() {
        final String[] items = {"按鈕1", "按鈕2", "按鈕3", "按鈕4"};
        final AlertDialog.Builder builder =
                new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("單選Dialog")
                .setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                })
                .setPositiveButton("確定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                })
                .show();
    }

多選Dialog

final ArrayList<Integer> choices = new ArrayList<>();

    private void showMultiChoiceDialog() {

        final String[] items = {"按鈕1", "按鈕2", "按鈕3", "按鈕4"};
        // 設定預設選中的選項
        final boolean initChoiceSets[] = {false, false, false, false};
        //choices.clear();
        AlertDialog.Builder builder =
                new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("多選Dialog")
                .setMultiChoiceItems(items, initChoiceSets, new DialogInterface
                        .OnMultiChoiceClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                        if (isChecked) {
                            choices.add(which);
                        } else {
                            //有問題:是把whichButton作為index還是Object?實際上會拋下標溢位異常
                            //MultiChoiceID.remove(whichButton);
                            //需強制轉換為Object型別,才會以物件的形式刪除;否則會作為下標處理
                            choices.remove((Integer) which);
                        }
                    }
                })
                .setPositiveButton("確定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                })
                .show();
    }

等待Dialog

private void showWaitingDialog() {
        final ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setTitle("等待Dialog");
        progressDialog.setMessage("等待中...");
        progressDialog.setIndeterminate(true);
        progressDialog.setCancelable(false);
        progressDialog.show();
        new Thread() {
            @Override
            public void run() {
                super.run();
                SystemClock.sleep(3000);
                progressDialog.dismiss();
            }
        }.start();
    }

進度條Dialog

private void showProgressDialog() {
        final int MAX_PROGRESS = 100;
        final ProgressDialog progressDialog =
                new ProgressDialog(MainActivity.this);
        progressDialog.setCancelable(false);
        progressDialog.setProgress(0);
        progressDialog.setTitle("進度條Dialog");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setMax(MAX_PROGRESS);
        progressDialog.show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                int progress = 0;
                while (progress < MAX_PROGRESS) {
                    try {
                        Thread.sleep(10);
                        progress++;
                        //子執行緒可以更新progressDialog進度
                        progressDialog.setProgress(progress);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                progressDialog.cancel();
            }
        }).start();
    }

編輯Dialog

private void showEditDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        final EditText view = new EditText(MainActivity.this);
        builder.setTitle("輸入dialog")
                .setView(view)
                .setPositiveButton("確定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        String content = view.getText().toString();
                    }
                })
                .show();
    }

自定義帶動畫的Dialog

private void showConsumerDialog() {
        Dialog dialog = new Dialog(MainActivity.this, R.style.BottomDialog);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog, null);
        dialog.setContentView(view);
        ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels;
        view.setLayoutParams(layoutParams);
        dialog.getWindow().setGravity(Gravity.BOTTOM);
        dialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
    }

自定義帶動畫的圓角Dialog

private void showConsumerDialogCircle() {
        final Dialog dialog = new Dialog(MainActivity.this, R.style.BottomDialog);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_circle, null);

        view.findViewById(R.id.takePhoto).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

        view.findViewById(R.id.selectPhoto).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog.setContentView(view);
        ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) view
                .getLayoutParams();
        layoutParams.bottomMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8,
                getResources().getDisplayMetrics());
        layoutParams.width = getResources().getDisplayMetrics().widthPixels - (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16,
                        getResources().getDisplayMetrics());
        view.setLayoutParams(layoutParams);
        dialog.getWindow().setGravity(Gravity.BOTTOM);
        dialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        dialog.setCanceledOnTouchOutside(true);
        dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        dialog.show();
    }
  • 自定義dialog佈局檔案 dialog_circle.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:background="@drawable/shape_dialog"
              android:layout_height="wrap_content">
    <TextView
        android:id="@+id/takePhoto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?android:attr/selectableItemBackground"
        android:clickable="true"
        android:padding="16dp"
        android:textSize="14sp"
        android:text="拍照"/>
    <TextView
        android:layout_width="match_parent"
        android:id="@+id/selectPhoto"
        android:layout_height="wrap_content"
        android:background="?android:attr/selectableItemBackground"
        android:clickable="true"
        android:padding="16dp"
        android:textSize="14sp"
        android:text="從相簿選取"/>
</LinearLayout>
  • dialog_circle.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">

    <corners android:radius="8dp"/>
    <solid android:color="@android:color/white"/>
</shape>
  • style
  <style name="BottomDialog" parent="@style/Base.V7.Theme.AppCompat.Light.Dialog">
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowBackground">@android:color/transparent</item>
    </style>
    <style name="BottomDialog.Animation" parent="Animation.AppCompat.Dialog">
        <item name="android:windowEnterAnimation">@anim/translate_dialog_in</item>
        <item name="android:windowExitAnimation">@anim/translate_dialog_out</item>
    </style>
  • Enter Exit 動畫
translate_dialog_in.xml

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
           android:duration="300"
           android:fromXDelta="0"
           android:fromYDelta="100%"
           android:toXDelta="0"
           android:toYDelta="0">
</translate>

translate_dialog_out.xml
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
           android:duration="300"
           android:fromXDelta="0"
           android:fromYDelta="0"
           android:toXDelta="0"
           android:toYDelta="100%">
</translate>