Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 自訂 Dialog 三步驟:樣式客製與參數雙向傳遞

編輯:關於 Android 程式設計

前面幾篇都在用系統現成的 API 拼對話框,但系統函式的彈性實在有限——一旦設計稿要求的版面不是「標題+訊息+兩個按鈕」,就只能自己來。本文完整走一遍自訂 Dialog:從雛形、樣式客製,到參數的傳入與回傳。

一、雛形:把 Dialog 畫出來

先看這節要達到的效果——四個 ImageView 水平排開:

1. 對話框佈局(custom_dialog.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/log_in_layout"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <ImageView android:layout_width="match_parent" android:layout_height="100dip"
        android:src="@drawable/animal1" android:clickable="true" android:layout_weight="1"/>
    <ImageView android:layout_width="match_parent" android:layout_height="100dip"
        android:src="@drawable/animal2" android:clickable="true" android:layout_weight="1"/>
    <ImageView android:layout_width="match_parent" android:layout_height="100dip"
        android:src="@drawable/animal3" android:clickable="true" android:layout_weight="1"/>
    <ImageView android:layout_width="match_parent" android:layout_height="100dip"
        android:src="@drawable/animal4" android:clickable="true" android:layout_weight="1"/>
</LinearLayout>

2. 繼承 Dialog 實作自己的對話框類別

Dialog 一共有三個建構子,這裡重寫了兩個,其中帶 theme 參數的那個稍後會用來套用樣式。關鍵在 onCreate():用 LayoutInflater 把自訂佈局取出來,再透過 setContentView() 指定給這個 Dialog。

public class CustomDialog extends Dialog {
    Context mContext;

    public CustomDialog(Context context) {
        super(context);
        mContext = context;
    }

    public CustomDialog(Context context, int theme) {
        super(context, theme);
        mContext = context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LayoutInflater inflater =
                (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.custom_dialog, null);
        this.setContentView(layout);
    }
}

3. 在 MainActivity 中彈出

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <Button android:id="@+id/btn_pop_dialog"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="彈出對話框"/>
</RelativeLayout>
public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btn = (Button) findViewById(R.id.btn_pop_dialog);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CustomDialog dialog = new CustomDialog(MainActivity.this);
                dialog.show();
            }
        });
    }
}

二、把醜醜的標題欄拿掉

仔細看上面的執行結果,會發現四隻小動物上方還有一條東西(下圖紅框處):

那是因為我們沒有指定樣式,系統套用了預設主題,而預設主題自帶標題欄。要拿掉它,就得自訂 Style。

1. 定義樣式

樣式寫在 res/values 下的 styles.xml(專案裡通常已存在,沒有就自己建一個):

<style name="dialog" parent="android:Theme.Dialog">
    <item name="android:windowFrame">@null</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowNoTitle">true</item>
</style>

幾個常用屬性的意義:

android:windowFrame:視窗的前景圖片,設為 @null 表示不要邊框。

android:windowIsFloating:讓版面浮在畫面之上並置中,基本上只有 Dialog 會用到。

android:windowContentOverlay:標題欄的陰影樣式,可給圖片或顏色。

android:windowNoTitle:是否隱藏標題欄,這正是我們要去掉的那一條。

2. 套用樣式

第一種寫法:建構時把樣式當參數傳進來。

CustomDialog dialog = new CustomDialog(MainActivity.this, R.style.dialog);
dialog.show();

第二種寫法:外部只能傳 Context,樣式在類別內部寫死,不給外人改。

public CustomDialog(Context context) {
    super(context, R.style.dialog);
    mContext = context;
}

封裝成元件給其他團隊使用時,第二種寫法比較不會被誤改。套上樣式後,標題欄就消失了。

三、參數傳遞:進得去,也要出得來

這裡有兩個方向要處理。傳進去:使用者點不同按鈕時,對話框裡顯示不同文案。傳出來:使用者點了哪張圖,要把對應的資源 ID 送回 MainActivity。

1. 傳進去:擴充建構子

public class CustomDialog extends Dialog {
    private Context mContext;
    private String mStr;

    public CustomDialog(Context context, String str, int theme) {
        super(context, theme);
        mContext = context;
        mStr = str;
    }
    // ...
}
Button btn2 = (Button) findViewById(R.id.btn_pop_dialog_2);
btn2.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        CustomDialog dialog =
                new CustomDialog(MainActivity.this, "From btn 2", R.style.dialog);
        dialog.show();
    }
});

2. 傳出來:回呼介面

把使用者的操作回傳給呼叫方,靠的是回呼(callback)。做法是在 Dialog 中宣告一個介面,透過建構子注入實作:

public class CustomDialog extends Dialog implements View.OnClickListener {

    // 對外宣告的回呼介面
    public interface ICustomDialogEventListener {
        void customDialogEvent(int id);
    }

    private ICustomDialogEventListener mCustomDialogEventListener;
    private Context mContext;
    private String mStr;

    public CustomDialog(Context context) {
        super(context);
        mContext = context;
    }

    public CustomDialog(Context context, String str,
                        ICustomDialogEventListener listener, int theme) {
        super(context, theme);
        mContext = context;
        mStr = str;
        mCustomDialogEventListener = listener;
    }

    private void bindImageClickEvent(View layout) {
        ImageView img1 = (ImageView) layout.findViewById(R.id.dialog_image1);
        ImageView img2 = (ImageView) layout.findViewById(R.id.dialog_image2);
        ImageView img3 = (ImageView) layout.findViewById(R.id.dialog_image3);
        ImageView img4 = (ImageView) layout.findViewById(R.id.dialog_image4);
        img1.setOnClickListener(this);
        img2.setOnClickListener(this);
        img3.setOnClickListener(this);
        img4.setOnClickListener(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LayoutInflater inflater =
                (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.custom_dialog, null);
        TextView tv = (TextView) layout.findViewById(R.id.dialog_text);
        tv.setText(mStr);
        bindImageClickEvent(layout);
        this.setContentView(layout);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        int drawableID = -1;
        switch (id) {
            case R.id.dialog_image1: drawableID = R.drawable.animal1; break;
            case R.id.dialog_image2: drawableID = R.drawable.animal2; break;
            case R.id.dialog_image3: drawableID = R.drawable.animal3; break;
            case R.id.dialog_image4: drawableID = R.drawable.animal4; break;
        }
        if (drawableID != -1) {
            mCustomDialogEventListener.customDialogEvent(drawableID);
        }
        dismiss();
    }
}

呼叫端在建立 Dialog 的時候,順手傳入匿名實作來接收結果:

Button btn = (Button) findViewById(R.id.btn_pop_dialog_1);
btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        CustomDialog dialog = new CustomDialog(MainActivity.this, "From btn 1",
            new CustomDialog.ICustomDialogEventListener() {
                @Override
                public void customDialogEvent(int id) {
                    ImageView imageView = (ImageView) findViewById(R.id.main_image);
                    imageView.setImageDrawable(getResources().getDrawable(id));
                }
            }, R.style.dialog);
        dialog.show();
    }
});

收到回傳的 drawable ID 後,直接設到主頁面的 ImageView,整個流程就通了。實務上自訂 Dialog 的使用頻率遠高於系統版本,所以這裡寫得細一些。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved