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

Android 自定義彈窗效果:從 AlertDialog 到 PopupWindow

編輯:關於 Android 程式設計

Android 的彈窗做法有好幾種。最簡單的是直接叫一個 AlertDialog,幾行程式碼就能跳出一個方方正正的對話框;但若想做出「從畫面底部滑出、背景半透明、點擊外部可關閉」這種更貼近 App 品牌調性的效果,PopupWindow 會是更合適的工具。就實用性與自由度而言,這條路值得一試。

先看最基礎的 AlertDialog

public void showDialog() {
    AlertDialog dialog = new AlertDialog.Builder(this)
            .setTitle("提示")
            .setMessage(getResources().getString(R.string.exit_confirm))
            .setPositiveButton("取消", new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            })
            .setNegativeButton("確定", new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // 在這裡執行確定後的業務邏輯
                }
            })
            .create();
    dialog.show();
}

功能齊全,但樣式幾乎無法客製。接著看自定義版本能做到什麼程度:

彈窗布局 modify_head.xml

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

    <LinearLayout
        android:id="@+id/top"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:gravity="center_horizontal"
        android:orientation="vertical">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="40.5dip"
            android:layout_marginLeft="7.2dip"
            android:layout_marginRight="7.2dip"
            android:gravity="center"
            android:text="@string/select_head"
            android:textColor="#aaaaaa" />

        <Button
            android:id="@+id/takephoto"
            android:layout_width="match_parent"
            android:layout_height="40.5dip"
            android:layout_marginLeft="7.2dip"
            android:layout_marginRight="7.2dip"
            android:background="@null"
            android:text="@string/takephoto"
            android:textColor="#fc4643" />

        <Button
            android:id="@+id/selectfromalbum"
            android:layout_width="match_parent"
            android:layout_height="40.5dip"
            android:layout_marginLeft="7.2dip"
            android:layout_marginRight="7.2dip"
            android:background="@null"
            android:text="@string/takefromalbum"
            android:textColor="#fc4643" />

        <Button
            android:id="@+id/cancel"
            android:layout_width="match_parent"
            android:layout_height="40.5dip"
            android:layout_marginLeft="7.2dip"
            android:layout_marginRight="7.2dip"
            android:layout_marginTop="7.2dip"
            android:background="@null"
            android:text="@string/cancel"
            android:textColor="#fc4643" />
    </LinearLayout>
</RelativeLayout>

SelectPopupWindow:繼承 PopupWindow

public class SelectPopupWindow extends PopupWindow {

    Button takePhoto;
    Button selectFromAlbum;
    Button cancel;
    View menuView;

    public SelectPopupWindow(Context ctx, OnClickListener onClickListener) {
        LayoutInflater inflater = (LayoutInflater)
                ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        menuView = inflater.inflate(R.layout.modify_head, null);

        takePhoto = (Button) menuView.findViewById(R.id.takephoto);
        takePhoto.setOnClickListener(onClickListener);

        selectFromAlbum = (Button) menuView.findViewById(R.id.selectfromalbum);
        selectFromAlbum.setOnClickListener(onClickListener);

        cancel = (Button) menuView.findViewById(R.id.cancel);
        cancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });

        setContentView(menuView);
        setWidth(LayoutParams.MATCH_PARENT);
        setHeight(LayoutParams.WRAP_CONTENT);
        setFocusable(true);
        // setAnimationStyle(R.style.AnimBottom);   // 需要時再打開進場動畫

        // 點擊彈窗窗外的區域時關閉
        menuView.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int height = menuView.findViewById(R.id.top).getTop();
                int y = (int) event.getY();
                if (event.getAction() == MotionEvent.ACTION_UP && y < height) {
                    dismiss();
                }
                return true;
            }
        });
    }
}

在 Activity 中使用

public class TestPopupWindow extends Activity {

    private SelectPopupWindow popupWindow;
    private ImageView image;
    private Button btn, btn1;
    private Uri fileUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main1);
        init();
    }

    private void init() {
        image = (ImageView) findViewById(R.id.image);
        btn = (Button) findViewById(R.id.btn);
        btn.setOnClickListener(onClickListener);
        btn1 = (Button) findViewById(R.id.btn1);
        btn1.setOnClickListener(onClickListener);
    }

    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn:
                    test();
                    break;
                case R.id.btn1:
                    startActivity(new Intent(TestPopupWindow.this, TestGsonActivity.class));
                    break;
                case R.id.takephoto:
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
                    startActivityForResult(intent, 100);
                    break;
                case R.id.selectfromalbum:
                    Intent intent1 = new Intent(Intent.ACTION_PICK);
                    intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                    startActivityForResult(intent1, 200);
                    break;
            }
        }
    };

    public void test() {
        popupWindow = new SelectPopupWindow(this, onClickListener);
        popupWindow.showAtLocation(findViewById(R.id.main),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }
}

幾個實務提醒:setFocusable(true) 讓彈窗可以接收點擊事件,但也會順便吃掉返回鍵,記得處理;若要背景變暗,可在呼叫前對 Activity 的 Window 設定 alpha;showAtLocation 的 Gravity 決定彈窗出現的位置,搭配 setAnimationStyle 就能做出由下滑入的過場。

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