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

Android 自定義提示框實作:用 DialogFragment 打造高質感彈窗

編輯:關於 Android 程式設計

系統自帶的 AlertDialog 雖然堪用,但樣式實在難登大雅之堂。想做出介面統一、視覺乾淨的提示框,比較好的做法是用 DialogFragment 搭配自訂布局,再透過 selector 處理按鈕的按下態。

一、Activity 布局

先在一個普通 Activity 上放一顆觸發按鈕:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView"
        android:layout_marginTop="165dp"
        android:layout_alignParentRight="true"
        android:text="點擊彈窗" />
</RelativeLayout>

二、MainActivity 的呼叫邏輯

關鍵觀念:用 Bundle 攜帶提示框要顯示的標題與內容,用介面回呼把使用者選擇傳回 Activity。

public class MainActivity extends ActionBarActivity {

    private MessageFragment mMessageFragment;
    private Bundle bundle;
    private Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = (Button) findViewById(R.id.button);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog();
            }
        });
    }

    private void showDialog() {
        if (mMessageFragment == null) {
            mMessageFragment = new MessageFragment();
        }
        if (bundle == null) {
            bundle = new Bundle();
        }
        bundle.putString("title", "標題");
        bundle.putString("content", "是否確認收件");
        mMessageFragment.setArguments(bundle);
        mMessageFragment.setOnResultListener(new OnItemMsgResultListener());
        mMessageFragment.show(getFragmentManager(), "message_dialog");
    }

    class OnItemMsgResultListener implements MessageFragment.OnMsgResultListener {
        @Override
        public void onResultFun(int resultCode) {
            if (resultCode == Activity.RESULT_OK) {
                Toast.makeText(MainActivity.this, "確認", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(MainActivity.this, "取消", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

三、提示框布局 message_dialog.xml

版面拆成三塊:標題區、內容區、按鈕區。背景各自使用 mipmap 中的切圖,中間用兩條 0.5dp 的分割線收邊。

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <RelativeLayout
        android:id="@+id/tv_head"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:background="@mipmap/confirm_head">

        <TextView
            android:id="@+id/tv_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="46dp"
            android:text="提示"
            android:textColor="#fff"
            android:textSize="18sp" />
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/rlyt_content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tv_head"
        android:background="@mipmap/message_content">

        <TextView
            android:id="@+id/tv_content"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:text="xxxx"
            android:textColor="#1a1a1a"
            android:textSize="15sp" />
    </RelativeLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/rlyt_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btn_submit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/button_msg_submit" />

        <Button
            android:id="@+id/btn_cancel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/btn_submit"
            android:background="@drawable/button_msg_cancel" />
    </LinearLayout>
</RelativeLayout>

四、drawable 下的 selector

按鈕的按下態、禁用態、常態各配一張圖,selector 會自動挑對的那張:

<selector xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:drawable="@mipmap/btn_msg_cancel_press" android:state_pressed="true" />
    <item android:drawable="@mipmap/btn_msg_cancel_normal" android:state_enabled="false" />
    <item android:drawable="@mipmap/btn_msg_cancel_normal" />
</selector>

button_msg_submit.xml 結構完全相同,把圖片換成 submit 系列即可。其餘 png 切圖資源可參考原∞,文連結:https://download.csdn.net/detail/u010778159/8923083

五、MessageFragment:真正幹活的地方

public class MessageFragment extends DialogFragment {

    private OnMsgResultListener mOnMsgResultListener;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // 拿掉預設標題列與邊框背景,讓自訂切圖完整呈現
        getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        View show_view = inflater.inflate(R.layout.message_dialog, null);
        TextView mTxtContent = (TextView) show_view.findViewById(R.id.tv_content);
        TextView mTxtTitle = (TextView) show_view.findViewById(R.id.tv_title);
        Button btnSubmit = (Button) show_view.findViewById(R.id.btn_submit);
        Button btnCancel = (Button) show_view.findViewById(R.id.btn_cancel);

        Bundle bundle = getArguments();
        if (bundle != null) {
            String title = bundle.getString("title");
            if (title != null) {
                mTxtTitle.setText(title);
            }
            mTxtContent.setText(bundle.getString("content"));
        }

        btnSubmit.setOnClickListener(btnClickListener);
        btnCancel.setOnClickListener(btnClickListener);
        setCancelable(false);   // 不允許按返回鍵關閉
        return show_view;
    }

    public void setOnResultListener(OnMsgResultListener listener) {
        mOnMsgResultListener = listener;
    }

    View.OnClickListener btnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_submit:
                    mOnMsgResultListener.onResultFun(Activity.RESULT_OK);
                    dismiss();
                    break;
                case R.id.btn_cancel:
                    mOnMsgResultListener.onResultFun(Activity.RESULT_CANCELED);
                    dismiss();
                    break;
            }
        }
    };

    public interface OnMsgResultListener {
        void onResultFun(int resultCode);
    }
}

兩個小細節值得注意:requestFeature(FEATURE_NO_TITLE) 與透明背景必須在 onCreateView 開頭就設定,否則會看到突兀的系統邊框;setCancelable(false) 則避免使用者誤觸返回鍵直接把對話框吃掉,讓業務邏輯保持在可控狀態。

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