本文主要是介紹Android中實現底部彈窗的的正確姿式,若是你在實現底部彈窗時遇到了一些問題,那麼請仔細閱讀本文,相信文章會對你有所幫助,文章有點長,請耐心讀完。html
閱讀完本文後,你能夠有如下收穫java
因爲本人水平有限,只知道一下幾種實現底部彈窗的方式android
下面,就利用以上四種方式分別實現Android中的底部彈窗。git
由於本文主要是介紹實現底部彈窗的方式,因此,不會對PopupWindow進行具體的講解,你們能夠到這裏瞭解PopupWindow。github
直接進入主題,按照套路,一步步實現利用PopupWindow實現底部彈窗。首先,寫一個佈局文件做爲PopupWindow中的內容,佈局文件以下express
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:background="#553b3a3a" android:layout_height="match_parent"> <LinearLayout android:layout_width="match_parent" android:layout_alignParentBottom="true" android:orientation="vertical" android:id="@+id/content" android:background="@android:color/white" android:layout_height="wrap_content"> <TextView android:layout_width="match_parent" android:textColor="#333" android:text="相機" android:padding="8dp" android:id="@+id/open_from_camera" android:gravity="center" android:textSize="15sp" android:layout_height="40dp" /> <TextView android:layout_marginTop="1dp" android:id="@+id/open_album" android:layout_width="match_parent" android:textColor="#333" android:text="打開圖庫" android:padding="8dp" android:gravity="center" android:textSize="15sp" android:layout_height="40dp" /> <TextView android:layout_marginTop="1dp" android:id="@+id/cancel" android:layout_width="match_parent" android:textColor="#333" android:text="取消" android:padding="8dp" android:gravity="center" android:textSize="15sp" android:layout_height="40dp" /> </LinearLayout> </RelativeLayout> 複製代碼
注:這裏使用的是填充父窗口的方式,若是不這樣作的話,就不能看出遮住後面的效果,看下圖更容易理解,左圖爲填充父佈局的方式,右圖爲 自適應的方式apache
下面看下利用PopupWindow實現底部彈窗的代碼,重要的方法我會具體講解bash
private void initPopupWindow() { //要在佈局中顯示的佈局 contentView = LayoutInflater.from(this).inflate(R.layout.popup_layout, null, false); //實例化PopupWindow並設置寬高 popupWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); popupWindow.setBackgroundDrawable(new BitmapDrawable()); //點擊外部消失,這裏由於PopupWindow填充了整個窗口,因此這句代碼就沒用了 popupWindow.setOutsideTouchable(true); //設置能夠點擊 popupWindow.setTouchable(true); //進入退出的動畫 popupWindow.setAnimationStyle(R.style.MyPopWindowAnim); } private void showPopWindow() { View rootview = LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_main, null); popupWindow.showAtLocation(rootview, Gravity.BOTTOM, 0, 0); } 複製代碼
重點看一下這句代碼markdown
popupWindow.showAtLocation(rootview, Gravity.BOTTOM, 0, 0);
複製代碼
這句代碼是設置彈出窗口從哪裏彈出,showAtLocation (View parent,int gravity,int x,int y) 方法有四個參數,第一個參數是父佈局,第二個爲從父佈局的哪裏彈出,x和y是相對於父佈局彈出位置的偏移量。因爲,咱們要將mPopWindow放在整個屏幕的最低部,因此咱們將R.layout.activity_main作爲它的父容器,將其顯示在BOTTOM的位置。app
再仔細看下上圖,利用PopupWindow實現從底部的彈窗並不能覆蓋到狀態欄,下面就來解決這個問題。
想要覆蓋到狀態欄還須要添如下代碼
//彈出的窗口是否覆蓋狀態欄 public void fitPopupWindowOverStatusBar(boolean needFullScreen) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { try { //利用反射從新設置mLayoutInScreen的值,當mLayoutInScreen爲true時則PopupWindow覆蓋全屏。 Field mLayoutInScreen = PopupWindow.class.getDeclaredField("mLayoutInScreen"); mLayoutInScreen.setAccessible(true); mLayoutInScreen.set(popupWindow, needFullScreen); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } } 複製代碼
再改變一下顯示PopupWindow的代碼,以下
//設置是否遮住狀態欄 fitPopupWindowOverStatusBar(true); View rootview = LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_main, null); popupWindow.showAtLocation(rootview, Gravity.BOTTOM, 0, 0); 複製代碼
再看下效果
先看下代碼,而後再講解
public class DialogFromBottom extends Dialog{ private final static int mAnimationDuration = 200; // 持有 ContentView,爲了作動畫 private View mContentView; private boolean mIsAnimating = false; private OnBottomSheetShowListener mOnBottomSheetShowListener; public DialogFromBottom(@NonNull Context context) { super(context, R.style.AppTheme_BottomSheet); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().getDecorView().setPadding(0, 0, 0, 0); // 在底部,寬度撐滿 WindowManager.LayoutParams params = getWindow().getAttributes(); params.height = ViewGroup.LayoutParams.WRAP_CONTENT; params.gravity = Gravity.BOTTOM | Gravity.CENTER;//dialog從哪裏彈出 //彈出窗口的寬高 int screenWidth = QMUIDisplayHelper.getScreenWidth(getContext()); int screenHeight = QMUIDisplayHelper.getScreenHeight(getContext()); params.width = screenWidth < screenHeight ? screenWidth : screenHeight; getWindow().setAttributes(params); setCanceledOnTouchOutside(true); } //設置彈出dialog中的layout @Override public void setContentView(int layoutResID) { mContentView = LayoutInflater.from(getContext()).inflate(layoutResID, null); super.setContentView(mContentView); } @Override public void setContentView(@NonNull View view) { mContentView = view; super.setContentView(view); } @Override public void setContentView(@NonNull View view, ViewGroup.LayoutParams params) { mContentView = view; super.setContentView(view, params); } /** * BottomSheet升起動畫 */ private void animateUp() { if (mContentView == null) { return; } TranslateAnimation translate = new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 1f, Animation.RELATIVE_TO_SELF, 0f ); AlphaAnimation alpha = new AlphaAnimation(0, 1); AnimationSet set = new AnimationSet(true); set.addAnimation(translate); set.addAnimation(alpha); set.setInterpolator(new DecelerateInterpolator()); set.setDuration(mAnimationDuration); set.setFillAfter(true); mContentView.startAnimation(set); } /** * BottomSheet降下動畫 */ private void animateDown() { if (mContentView == null) { return; } TranslateAnimation translate = new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 1f ); AlphaAnimation alpha = new AlphaAnimation(1, 0); AnimationSet set = new AnimationSet(true); set.addAnimation(translate); set.addAnimation(alpha); set.setInterpolator(new DecelerateInterpolator()); set.setDuration(mAnimationDuration); set.setFillAfter(true); set.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { mIsAnimating = true; } @Override public void onAnimationEnd(Animation animation) { mIsAnimating = false; /** * Bugfix: Attempting to destroy the window while drawing! */ mContentView.post(new Runnable() { @Override public void run() { // java.lang.IllegalArgumentException: View=com.android.internal.policy.PhoneWindow$DecorView{22dbf5b V.E...... R......D 0,0-1080,1083} not attached to window manager // 在dismiss的時候可能已經detach了,簡單try-catch一下 try { DialogFromBottom.super.dismiss(); } catch (Exception e) { //這裏處理異常 } } }); } @Override public void onAnimationRepeat(Animation animation) { } }); mContentView.startAnimation(set); } @Override public void show() { super.show(); animateUp(); if (mOnBottomSheetShowListener != null) { mOnBottomSheetShowListener.onShow(); } } @Override public void dismiss() { if (mIsAnimating) { return; } animateDown(); } public interface OnBottomSheetShowListener { void onShow(); } } 複製代碼
額,代碼有點長,其實很容易理解,這裏主要說下onCreate方法中的內容,能夠仔細看下注釋。
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().getDecorView().setPadding(0, 0, 0, 0);//把父佈局的padding都設爲0,目的是能夠dialog撐滿全屏。 // 在底部,寬度撐滿 WindowManager.LayoutParams params = getWindow().getAttributes(); params.height = ViewGroup.LayoutParams.WRAP_CONTENT; params.gravity = Gravity.BOTTOM | Gravity.CENTER;//dialog從底部彈出 //彈出窗口的寬高,DisplayHelper.getScreenWidth(getContext());和DisplayHelper.getScreenHeight(getContext());是拿到屏幕的寬高。 int screenWidth = DisplayHelper.getScreenWidth(getContext()); int screenHeight = DisplayHelper.getScreenHeight(getContext()); params.width = screenWidth < screenHeight ? screenWidth : screenHeight;//適配手機橫屏 getWindow().setAttributes(params);//從新設置dialog的屬性 setCanceledOnTouchOutside(true);//設置觸摸dialog之外,dialog是否消失 } 複製代碼
利用Dialog實現底部彈窗就是繼承系統Dialog而後重寫了onCreate方法,設置dialog從底部彈出。由於是繼承Dialog,因此有Dialog的特性,既觸摸底部彈窗之外的部分,彈窗會自動消失,這裏就不在演示,能夠在文末獲取源碼,本身實驗一下就知道了。
在實現彈窗以前,先了解一下DialogFragment
DialogFragment在android 3.0時被引入。是一種特殊的Fragment,用於在Activity的內容之上展現一個模態的對話框。
使用DialogFragment至少須要實現onCreateView或者onCreateDIalog方法。onCreateView即便用定義的xml佈局文件展現Dialog。onCreateDialog即利用AlertDialog或者Dialog建立出Dialog。下面經過實現onCreateView方法來實現底部彈窗。
@Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.dialog_layout, container, false); return view; } @Override public void onStart() { super.onStart(); initParams();//初始化彈窗的參數 } private void initParams() { Window window = getDialog().getWindow(); if (window != null) { WindowManager.LayoutParams lp = window.getAttributes(); //調節灰色背景透明度[0-1],默認0.5f lp.dimAmount = dimAmount; //是否在底部顯示 if (showBottom) { lp.gravity = Gravity.BOTTOM; if (animStyle == 0) { animStyle = R.style.DefaultAnimation; } } //設置dialog寬度 if (width == 0) { lp.width = DisplayHelper.getScreenWidth(getActivity()) - 2 * DisplayHelper.dp2px(getActivity(), margin); } else { lp.width = DisplayHelper.dp2px(getActivity(), width); } //設置dialog高度 if (height == 0) { lp.height = WindowManager.LayoutParams.WRAP_CONTENT; } else { lp.height = DisplayHelper.dp2px(getActivity(), height); } //設置dialog進入、退出的動畫 window.setWindowAnimations(animStyle); window.setAttributes(lp); } setCancelable(outCancel);//設置點擊外部是否消失 } 複製代碼
由於DialogFragment也是Fragment,因此,DialogFragment有和Fragment同樣的生命週期,在onStart方法中初始化彈窗的數據,在onCreateView中加載佈局,一樣,和Fragment使用方法也是同樣的,下面看下在Activity中的使用
void showDialog() { FragmentTransaction ft = getFragmentManager().beginTransaction(); // Create and show the dialog. DialogFragmentFromBottom newFragment = new DialogFragmentFromBottom(); newFragment.show(ft, "dialog"); } 複製代碼
這種方式實現底部彈窗,我以前並無用過,仍是這篇文章下面的評論說如今都在用bottonSheetDialog了,我才知道能夠用這種方式實現底部彈窗。亡羊補牢,爲時不晚,爲了之後讓閱讀本文的人能夠知道這種方式,就趕忙把這種實現底部彈窗的方式加到本文中了。使用BottonSheetDialog真的很是簡單,就像直接使用Dialog同樣,下面看一下使用的代碼
//使用BottomSheetDialog方式實現底部彈窗 void showBottomSheetDialog(){ BottomSheetDialog bottomSheet = new BottomSheetDialog(this);//實例化BottomSheetDialog bottomSheet.setCancelable(true);//設置點擊外部是否能夠取消 bottomSheet.setContentView(R.layout.dialog_layout);//設置對框框中的佈局 bottomSheet.show();//顯示彈窗 } 複製代碼
代碼很簡單,如今看下BottomSheetDialog的源碼,BottomSheetDialog是繼承AppCompatDialog的,間接的繼承了Dialog,而後重寫量一些方法,下面看代碼
//設置須要展現的view @Override public void setContentView(@LayoutRes int layoutResId) { super.setContentView(wrapInBottomSheet(layoutResId, null, null)); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Window window = getWindow(); if (window != null) { if (Build.VERSION.SDK_INT >= 21) { //設置5.0以上系統狀態欄 window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); } //設置佈局的屬性 window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); } } 複製代碼
能夠發現setContentView引用了wrapInBottomSheet方法,wrapInBottomSheet方法就是實現底部彈窗的重要方法,下面看下這個方法的內容
private View wrapInBottomSheet(int layoutResId, View view, ViewGroup.LayoutParams params) { final FrameLayout container = (FrameLayout) View.inflate(getContext(), R.layout.design_bottom_sheet_dialog, null); final CoordinatorLayout coordinator = (CoordinatorLayout) container.findViewById(R.id.coordinator); if (layoutResId != 0 && view == null) { view = getLayoutInflater().inflate(layoutResId, coordinator, false); } FrameLayout bottomSheet = (FrameLayout) coordinator.findViewById(R.id.design_bottom_sheet);//這個view就是放置咱們本身佈局的容器 mBehavior = BottomSheetBehavior.from(bottomSheet); mBehavior.setBottomSheetCallback(mBottomSheetCallback); mBehavior.setHideable(mCancelable); if (params == null) { bottomSheet.addView(view); } else { bottomSheet.addView(view, params); } // We treat the CoordinatorLayout as outside the dialog though it is technically inside coordinator.findViewById(R.id.touch_outside).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mCancelable && isShowing() && shouldWindowCloseOnTouchOutside()) { cancel(); } } }); //此處省略部分代碼 ...... return container; } 複製代碼
能夠看到wrapInBottomSheet這個方法主要是將咱們本身的佈局放在design_bottom_sheet_dialog這個layout中的id爲design_bottom_sheet的view中了,看下design_bottom_sheet_dialog這個佈局你就會明白了
<?xml version="1.0" encoding="utf-8"?> <!-- ~ Copyright (C) 2015 The Android Open Source Project ~ ~ Licensed under the Apache License, Version 2.0 (the "License"); ~ you may not use this file except in compliance with the License. ~ You may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 ~ ~ Unless required by applicable law or agreed to in writing, software ~ distributed under the License is distributed on an "AS IS" BASIS, ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ~ See the License for the specific language governing permissions and ~ limitations under the License. --> <FrameLayout 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:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true"> <android.support.design.widget.CoordinatorLayout android:id="@+id/coordinator" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true"> <View android:id="@+id/touch_outside" android:layout_width="match_parent" android:layout_height="match_parent" android:importantForAccessibility="no" android:soundEffectsEnabled="false" tools:ignore="UnusedAttribute"/> <FrameLayout android:id="@+id/design_bottom_sheet" style="?attr/bottomSheetStyle" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center_horizontal|top" android:clickable="true" app:layout_behavior="@string/bottom_sheet_behavior"/> </android.support.design.widget.CoordinatorLayout> </FrameLayout> 複製代碼
經過閱讀源碼你會發現BottemSheetDialog的實質就是Dialog中填充了一個全屏的佈局,而後在這個佈局的底部把你本身的佈局放置進去。
好了,到這裏四種實現底部彈窗的方式已經講完了,你們能夠下載源碼研究一下,源碼在這裏,在作項目時選擇最適合的就好,在這裏仍是推薦使用BottomSheetDialog吧!畢竟使用很簡單。
轉載請註明出處:www.wizardev.com