Android中自定义DialogFragment解决宽度和高度
2017-12-07 本文已影响619人
huangandroid
Android中自定义DialogFragment解决宽度和高度问题
Android中自定义DialogFragment解决宽度和高度问题但是我们很多时候想把DialogFragment的高度固定,那么我们需要设置DialogFragment的高度,在Fragment的onResume()声明周期方法中设置window的宽高即可。
@Override
public void onResume() {
super.onResume();
getDialog().getWindow().setLayout(DeviceUtil.getDeviceWidth(), ResUtils.dp2px(295));
}
设置DialogFrament 从底部弹出,并且弹出动画为向上滑出,消失动画为向下滑出
WindowManager.LayoutParams params = getDialog().getWindow()
.getAttributes();
params.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
params.windowAnimations = R.style.bottomSheet_animation;
getDialog().getWindow().setAttributes(params);
完整的代码如下:
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
WindowManager.LayoutParams params = getDialog().getWindow()
.getAttributes();
params.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
params.windowAnimations = R.style.bottomSheet_animation;
getDialog().getWindow().setAttributes(params);
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
getDialog().setCanceledOnTouchOutside(true);
getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
mContentView = inflater.inflate(R.layout.fragment_create_quick, container, false);
return mContentView;
}
@Override
public void onResume() {
super.onResume();
getDialog().getWindow().setLayout(DeviceUtil.getDeviceWidth(), HlyUtils.dp2px(380));
}
<style name="bottomSheet_animation" parent="@android:style/Animation">
<item name="android:windowEnterAnimation">@anim/slide_in_bottom</item>
<item name="android:windowExitAnimation">@anim/slide_out_bottom</item>
</style>
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false">
<translate
android:duration="300"
android:fromYDelta="100.0%p"
android:toYDelta="0.0" />
</set>
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false">
<translate
android:duration="300"
android:fromYDelta="0%p"
android:toYDelta="100%p" />
</set>