您的位置:首页 > 其它

自定义 DialogFragment 实现底部弹出 dialog

2017-06-13 15:44 483 查看
前端时间公司做的项目要求和 iOS 版本的 UI 风格保持高度的一致,虽然我个人及其排斥这种仿 iOS 的 UI,然而人在屋檐下,不得不出卖自己的节操。其中就有一个底部弹出 dialog 的效果,宽度还是全屏的,就项这个样子(其实这张图就是我最终实现的效果):



于是乎百度 google 了一番,居然没有找到用 DialogFragment 实现的类似的效果,网上大多实现类似效果的都是使用传统的 dialog 实现的,本菜鸟虽然技术菜,但也知道 google 耙耙是推荐使用 DialogFragment 来代替 dialog,无奈只能自己尝试着实现了。

首先从底部弹出的效果,必然需要写一个弹出的动画,我们可以再 style 里面设置其弹出动画:

<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_slide_show</item>
<item name="android:windowExitAnimation">@anim/bottom_dialog_slide_hide</item>
</style>
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

<translate
android:duration="300"
android:fromYDelta="0"
android:toYDelta="100%p"/>
</set>

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:duration="300"
android:fromYDelta="100%p"
android:toYDelta="0"/>
</set>


这样就把 style 定义好了,并且设置了它的弹出和销毁的动画,接下来就需要自定义 DialogFragment 了,上代码:

public abstract class BottomDialog extends DialogFragment {

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//设置style
setStyle(DialogFragment.STYLE_NORMAL, R.style.BottomDialog);

}

@Override
public void onStart() {
super.onStart();
//设置 dialog 的宽高
getDialog().getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//设置 dialog 的背景为 null
getDialog().getWindow().setBackgroundDrawable(null);

}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

//去除标题栏
getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);

Window window = getDialog().getWindow();
WindowManager.LayoutParams lp = window.getAttributes();
lp.gravity = Gravity.BOTTOM; //底部
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
window.setAttributes(lp);

return createView(inflater, container);
}

//重写此方法,设置布局文件
protected abstract View createView(LayoutInflater inflater, ViewGroup container);

}

很简单的自定义,都有注释,就不解释了,使用的时候直接继承这个类,然后重写 createView 方法来设置布局文件就好了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: