Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android資訊 >> Android 自定義 AlertDialog 提示框

Android 自定義 AlertDialog 提示框

編輯:Android資訊

在Android開發中,因項目需要,大部分情況下需要自定義Dialog來滿足項目需求,系統雖然也有,但是界面美觀方面,不忍直視。

下面貼出Android項目中使用的自定義Dialog提示框代碼,附:效果圖。

圖一:

圖二:

自定義AlertDialog的java類:

/*******************************************************************************
 *
 * Copyright (c) Weaver Info Tech Co. Ltd
 *
 * Dialog
 *
 * app.ui.Dialog.java
 * TODO: File description or class description.
 * @since:  Jul 17, 2013
 * @version: 1.0.0
 *
 * @changeLogs:
 *     1.0.0: First created this class.
 *
 ******************************************************************************/
package app.ui;

import mobi.kuaidian.shizhenbao.R;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class AlertDialog extends Dialog implements OnClickListener, OnItemClickListener {

    private TextView mTitleTextView;
    private TextView mMessageTextView;

    private Button mNegativeButton;
    private Button mNeutralButton;
    private Button mPositiveButton;

    private View mLeftLineView;
    private View mRightLineView;

    private ListView mListView;
    private ViewGroup mContent;

    private DialogInterface.OnClickListener mNegativeListener;
    private DialogInterface.OnClickListener mNeutraListener;
    private DialogInterface.OnClickListener mPositiveListener;

    private CharSequence[] mItems;
    private DialogInterface.OnClickListener mSingleChoiceClickListener;
    private DialogInterface.OnMultiChoiceClickListener mMultiChoiceClickListener;
    private int mCheckedItem;
    private boolean[] mCheckedItems;
    private boolean mIsMultiChoice = false;
    private boolean mIsSingleChoice = false;

    /**
     * @param context
     */
    public AlertDialog(Context context) {
        super(context, R.style.Theme_Dialog_Alert);
        setupViews();
    }

    /* (non-Javadoc)
     * @see android.view.View.OnClickListener#onClick(android.view.View)
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_positive:
                if (mPositiveListener != null) {
                    mPositiveListener.onClick(this, 0);
                } else {
                    cancel();
                }
                break;

            case R.id.button_negative:
                if (mNegativeListener != null) {
                    mNegativeListener.onClick(this, 1);
                } else {
                    cancel();
                }
                break;

            case R.id.button_nuetral:
                if (mNeutraListener != null) {
                    mNeutraListener.onClick(this, 2);
                } else {
                    cancel();
                }
                break;

            default:
                break;
        }
    }

    /* (non-Javadoc)
     * @see android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget.AdapterView, android.view.View, int, long)
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
        if (mIsSingleChoice && mSingleChoiceClickListener != null) {
            mSingleChoiceClickListener.onClick(this, position);
        } // else ignored

        if (mIsMultiChoice && mMultiChoiceClickListener != null) {
            // TODO
        } // else ignored
    }

    private void setupViews() {
        setContentView(R.layout.dialog);

        mTitleTextView = (TextView) findViewById(R.id.text_title);
        mMessageTextView = (TextView) findViewById(R.id.text_message);

        mNegativeButton = (Button) findViewById(R.id.button_negative);
        mNeutralButton = (Button) findViewById(R.id.button_nuetral);
        mPositiveButton = (Button) findViewById(R.id.button_positive);

        mLeftLineView = findViewById(R.id.view_line_left);
        mRightLineView = findViewById(R.id.view_line_right);

        mListView = (ListView) findViewById(R.id.list);

        mContent = (ViewGroup) findViewById(R.id.layout_content);

        mNegativeButton.setOnClickListener(this);
        mNeutralButton.setOnClickListener(this);
        mPositiveButton.setOnClickListener(this);
    }

    private void setTitle(String title) {
        mTitleTextView.setText(title);
    }

    private void setIcon(Drawable icon) {
        mTitleTextView.setCompoundDrawablesWithIntrinsicBounds(null, null, icon, null);
    }

    private void setMessage(CharSequence message) {
        mMessageTextView.setVisibility(View.VISIBLE);
        mMessageTextView.setText(message);
    }

    private void setView(View view) {
        if (view != null) {
            final LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT,
                    LayoutParams.MATCH_PARENT);
            mContent.addView(view, layoutParams);
        }
    }

    private void setNegativeButton(CharSequence text, OnClickListener listener) {
        mNegativeButton.setVisibility(View.VISIBLE);
        mNegativeButton.setText(text);
        this.mNegativeListener = listener;
    }

    private void setNeutralButton(CharSequence text, OnClickListener listener) {
        mNeutralButton.setVisibility(View.VISIBLE);
        mNeutralButton.setText(text);
        this.mNeutraListener = listener;
    }

    private void setPositiveButton(CharSequence text, OnClickListener listener) {
        mPositiveButton.setVisibility(View.VISIBLE);
        mPositiveButton.setText(text);
        this.mPositiveListener = listener;
    }

    private void setButtonLines(boolean left, boolean right) {
        mLeftLineView.setVisibility(left ? View.VISIBLE : View.GONE);
        mRightLineView.setVisibility(right ? View.VISIBLE : View.GONE);
    }

    private void setSingleChoiceItems(CharSequence[] items, int checkedItem, final OnClickListener listener) {
        mItems = items;
        mSingleChoiceClickListener = listener;
        mCheckedItem = checkedItem;
        mIsSingleChoice = true;
        if (items != null && items.length > 0) {
            mListView.setVisibility(View.VISIBLE);
            final DialogAdapter adapter = new DialogAdapter(getContext(), items);
            mListView.setAdapter(adapter);
            mListView.setOnItemClickListener(this);
            mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
            mListView.setSelection(mCheckedItem);
        }
    }

    private void setMultiChoiceItems(CharSequence[] items, boolean[] checkedItems,
            final OnMultiChoiceClickListener listener) {
        mItems = items;
        mMultiChoiceClickListener = listener;
        mCheckedItems = checkedItems;
        mIsMultiChoice = true;
    }

    public static class Builder {

        private AlertDialog mAlertDialog;

        private final Context mContext;
        private CharSequence mTitle;
        private Drawable mIconDrawable;
        private CharSequence mMessage;

        private CharSequence mNegative;
        private CharSequence mNeutral;
        private CharSequence mPositive;

        private DialogInterface.OnClickListener mNegativeListener;
        private DialogInterface.OnClickListener mNeutraListener;
        private DialogInterface.OnClickListener mPositiveListener;

        private View mView;

        private CharSequence[] mItems;
        private DialogInterface.OnClickListener mSingleChoiceClickListener;
        private DialogInterface.OnMultiChoiceClickListener mMultiChoiceClickListener;
        private int mCheckedItem;
        private boolean[] mCheckedItems;
        private boolean mIsMultiChoice = false;
        private boolean mIsSingleChoice = false;

        public Builder(Context context) {
            mContext = context;
        }

        public Builder setTitle(CharSequence title) {
            mTitle = title;
            return this;
        }

        public Builder setTitle(int titleId) {
            setTitle(mContext.getString(titleId));
            return this;
        }

        public Builder setMessage(CharSequence message) {
            mMessage = message;
            return this;
        }

        public Builder setMessage(int messageId) {
            setMessage(mContext.getString(messageId));
            return this;
        }

        public Builder setIcon(Drawable icon) {
            this.mIconDrawable = icon;
            return this;
        }

        public Builder setIcon(int iconId) {
            setIcon(mContext.getResources().getDrawable(iconId));
            return this;
        }

        public Builder setSingleChoiceItems(CharSequence[] items, int checkedItem, final OnClickListener listener) {
            mItems = items;
            mSingleChoiceClickListener = listener;
            mCheckedItem = checkedItem;
            mIsSingleChoice = true;
            return this;
        }

        public void setView(View view) {
            mView = view;
        }

        public Builder setMultiChoiceItems(CharSequence[] items, boolean[] checkedItems,
                final OnMultiChoiceClickListener listener) {
            mItems = items;
            mMultiChoiceClickListener = listener;
            mCheckedItems = checkedItems;
            mIsMultiChoice = true;
            return this;
        }

        public Builder setNegativeButton(CharSequence text, OnClickListener listener) {
            this.mNegative = text;
            this.mNegativeListener = listener;
            return this;
        }

        public Builder setNegativeButton(int textId, OnClickListener listener) {
            setNegativeButton(mContext.getString(textId), listener);
            return this;
        }

        public Builder setNeutralButton(CharSequence text, OnClickListener listener) {
            this.mNeutral = text;
            this.mNeutraListener = listener;
            return this;
        }

        public Builder setNeutralButton(int textId, OnClickListener listener) {
            setNeutralButton(mContext.getString(textId), listener);
            return this;
        }

        public Builder setPositiveButton(CharSequence text, OnClickListener listener) {
            this.mPositive = text;
            this.mPositiveListener = listener;
            return this;
        }

        public Builder setPositiveButton(int textId, OnClickListener listener) {
            setPositiveButton(mContext.getString(textId), listener);
            return this;
        }

        public AlertDialog create() {
            final AlertDialog alertDialog = new AlertDialog(mContext);

            if (mTitle != null) {
                alertDialog.setTitle(mTitle.toString());
            } // else ignored

            if (mMessage != null) {
                alertDialog.setMessage(mMessage);
            } // else ignored

            if (mIconDrawable != null) {
                alertDialog.setIcon(mIconDrawable);
            } // else ignored

            if (mNegative != null) {
                alertDialog.setNegativeButton(mNegative, mNegativeListener);
            } // else ignored

            if (mNeutral != null) {
                alertDialog.setNeutralButton(mNeutral, mNeutraListener);
            } // else ignored

            if (mPositive != null) {
                alertDialog.setPositiveButton(mPositive, mPositiveListener);
            } // else ignored

            // 按鈕的分隔線
            if (mPositive != null && mNeutral != null && mNegative != null) {
                alertDialog.setButtonLines(true, true);
            } else if (mPositive != null && mNeutral != null) {
                alertDialog.setButtonLines(true, false);
            } else if (mNeutral != null && mNegative != null) {
                alertDialog.setButtonLines(false, true);
            } else if (mPositive != null && mNegative != null) {
                alertDialog.setButtonLines(true, false);
            } else {
                alertDialog.setButtonLines(false, false);
            }

            if (mItems != null && mItems.length > 0) {
                if (mIsSingleChoice) {
                    alertDialog.setSingleChoiceItems(mItems, mCheckedItem, mSingleChoiceClickListener);
                } // else ignored

                if (mIsMultiChoice) {
                    alertDialog.setMultiChoiceItems(mItems, mCheckedItems, mMultiChoiceClickListener);
                } // else ignored
            }  // else ignored

            if (mView != null) {
                alertDialog.setView(mView);
            }

            mAlertDialog = alertDialog;
            return alertDialog;
        }

        public AlertDialog show() {
            create();
            mAlertDialog.show();
            return mAlertDialog;
        }
    }

    public static class DialogAdapter extends ArrayAdapter<CharSequence> {

        /**
         * @param context
         * @param resource
         */
        public DialogAdapter(Context context, CharSequence[] items) {
            super(context, R.layout.list_item_dialog, R.id.text, items);
        }
    }
}

必要的兩個xml文件,這個是dialog.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="@dimen/dialog_width"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/text_title"
        android:layout_width="match_parent"
        android:layout_height="@dimen/header_height"
        android:background="@color/main_color"
        android:gravity="center"
        android:textColor="#ffffff"
        android:textSize="20sp" />

    <FrameLayout
        android:id="@+id/layout_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/text_message"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="8dp"
            android:textColor="@color/main_text_color"
            android:textSize="18sp"
            android:visibility="gone" />

        <ListView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:cacheColorHint="@color/transparent"
            android:divider="@drawable/point"
            android:listSelector="@drawable/list_selector"
            android:visibility="gone" />
    </FrameLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="1px"
        android:background="#adadad" />

    <LinearLayout
        android:id="@+id/layout_footer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/button_positive"
            android:layout_width="match_parent"
            android:layout_height="45dp"
            android:layout_weight="1.0"
            android:background="@drawable/button_common_selector"
            android:visibility="gone" />

        <View
            android:id="@+id/view_line_left"
            android:layout_width="1px"
            android:layout_height="match_parent"
            android:background="#adadad"
            android:visibility="visible" />

        <Button
            android:id="@+id/button_nuetral"
            android:layout_width="match_parent"
            android:layout_height="45dp"
            android:layout_weight="1.0"
            android:background="@drawable/button_common_selector"
            android:visibility="gone" />

        <View
            android:id="@+id/view_line_right"
            android:layout_width="1px"
            android:layout_height="match_parent"
            android:background="#adadad"
            android:visibility="visible" />

        <Button
            android:id="@+id/button_negative"
            android:layout_width="match_parent"
            android:layout_height="45dp"
            android:layout_weight="1.0"
            android:background="@drawable/button_common_selector"
            android:visibility="gone" />
    </LinearLayout>

</LinearLayout>

這個是list_item_dialog.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <CheckedTextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="@dimen/row_height"
        android:checkMark="@drawable/ic_check_selector"
        android:duplicateParentState="true"
        android:gravity="center_vertical"
        android:padding="12dp"
        android:textColor="@color/gray"
        android:textSize="18dp" />

</LinearLayout>

資源文件中的樣式屬性,這裡就不多說了,可以自己設置隨意的顏色和樣式,或者加上圖片。

使用方法(圖1):

final AlertDialog.Builder builder  = new AlertDialog.Builder(getActivity());
                builder.setTitle("選擇頭像來源");
                final String[] avatarSources = getResources().getStringArray(R.array.avatar_sources);
                builder.setSingleChoiceItems(avatarSources, 0, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {

                            case 0:
                                //點擊第一個條目
                                break;
                            case 1:
								//點擊第2個條目
                                break;
                            case 2:
								//點擊第3個條目
                                break;

                            default:
                                break;
                        }
                        dialog.dismiss();
                    }
                });
                builder.show();

使用方法(圖2):

 final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setTitle("提示");
                builder.setMessage("您確定要退出登錄麼?");
                builder.setNegativeButton("取消", null);
                builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //退出需要執行的操作
                    }
                });
                builder.show();

以上就是Android中自定義 AlertDialog 提示框的實現方法,希望對你有所幫助。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved