Android 从下往上弹出 DialogFragment 的关键代码
//java代码: public class CountrySelectDialog extends AppCompatDialogFragment{ public static CountrySelectDialog newInstance() { Bundle args = new Bundle(); CountrySelectDialog fragment = new CountrySelectDialog(); fragment.setArguments(args); return fragment; } @Override public void onStart() { super.onStart(); setStyle(AppCompatDialogFragment.STYLE_NORMAL, R.style.BottomDialog);//设置自定义style Window window = getDialog().getWindow(); window.setBackgroundDrawable(null);//必须的 WindowManager.LayoutParams lp = window.getAttributes(); lp.gravity = Gravity.BOTTOM;//在下边 lp.width = WindowManager.LayoutParams.MATCH_PARENT; window.setAttributes(lp); getDialog().setOnDismissListener(dialog -> { //todo,关闭dialog的回调监听 } }); } @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.xxx, container, false); } public void show(FragmentManager supportFragmentManager) { show(supportFragmentManager, getClass().getName()); setStyle(AppCompatDialogFragment.STYLE_NORMAL, R.style.BottomDialog);//show的时候设置,不然第一次style无效 } } //styles.xml代码: <style name="BottomDialog" parent="Theme.AppCompat.Light.Dialog"> <item name="android:windowAnimationStyle">@style/BottomDialogAnimation</item> </style> <style name="BottomDialogAnimation"> <item name="android:windowEnterAnimation">@anim/bottom_dialog_in</item> <item name="android:windowExitAnimation">@anim/bottom_dialog_out</item> </style> // res/anim/bottom_dialog_in.xml <?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:anim/accelerate_interpolator" > <translate android:duration="300" android:fillAfter="true" android:fromXDelta="0" android:fromYDelta="100%" android:toXDelta="0" android:toYDelta="0"> </translate> <alpha android:duration="300" android:fromAlpha="0.0" android:toAlpha="1.0"/> </set> // res/anim/bottom_dialog_out.xml <?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:anim/accelerate_interpolator"> <translate android:duration="300" android:fillAfter="true" android:fromXDelta="0" android:fromYDelta="0" android:toXDelta="0" android:toYDelta="100%"> </translate> <alpha android:duration="300" android:fromAlpha="1.0" android:toAlpha="0.0"/> </set>