Android 自定義DiaLog

AlertDialog在實際開發中經常會被使用到,而且多數時候是要DIY一個,那讓我們來試試吧~

首先,我們捋一捋思路:

a、先準備一個自定義XML佈局
b、創建一個AlertDialog類,在構造方法中初始化一些我們要的參數。
c、實例化AlertDialog.Builder和AlertDialog,並設置一些屬性
d、使之顯示

先來個自定義XML佈局pay_layout.xml (a):

<?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:layout_height="wrap_content">
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:layout_width="match_parent"
        android:text="充值"
        android:layout_height="wrap_content" />
</LinearLayout>

創建一個類(b、c、d):

//    來一個自定義提示類
    class MyDiaLog{
        private Context context;
        private String title_str;
        private int layout_name;

    public MyDiaLog(Context context, String title_str, int layout_name) {
        this.context = context;
        this.title_str = title_str;
        this.layout_name = layout_name;
//        調用方法
        Popup_DiaLog();
    }

    private void Popup_DiaLog(){
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
//                  設置標題
                builder.setTitle(title_str);
//                  找到自定義佈局並將其添加到View中
                View view = View.inflate(context,layout_name,null);
//                  設置View
                builder.setView(view);
//                  設置可見
                builder.show();
//                  創建一個dialog
            AlertDialog dialog = builder.create();

        }
    }

嗯,這樣寫帶點簡單的封裝,提高代碼的複用性。要用的時候只要實例化一下類就可以啦~
例如:

 MyDiaLog myDiaLog = new MyDiaLog(MainActivity.this,"充值金額:",R.layout.pay_layout);

主佈局:

<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"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:text="充值"
        android:layout_height="wrap_content" />

</LinearLayout>

Java代碼:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button button = findViewById(R.id.button1);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            MyDiaLog myDiaLog = new MyDiaLog(MainActivity.this,"充值金額:",R.layout.pay_layout);
        }
    });
}

效果圖:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章