此处使用的编辑器为Android studio
1. 新建?自定义弹窗类:如 InputDialog
public class InputDialog extends DialogFragment {
protected FragmentActivity mActivity;
public void setmActivity(FragmentActivity mActivity) {
this.mActivity = mActivity;
}
//自定义样式,注:此处主要设置弹窗的宽高
@Override
public int getTheme() {
return R.style.InputDialogStyle;
}
public void show(){
mActivity.runOnUiThread(() -> {
if (isActivityAlive()){
FragmentManager fm = mActivity.getSupportFragmentManager();
Fragment prev = fm.findFragmentByTag(getClass().getSimpleName());
if (prev != null) fm.beginTransaction().remove(prev);
if (!InputDialog.this.isAdded()) {
InputDialog.super.show(fm, getClass().getSimpleName());
}
}
});
}
@Override
public void dismiss() {
mActivity.runOnUiThread(() -> {
if (isActivityAlive()) {
InputDialog.super.dismissAllowingStateLoss();
}
});
}
private boolean isActivityAlive() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
return mActivity != null && !mActivity.isFinishing() && !mActivity.isDestroyed();
}else {
return mActivity != null && !mActivity.isFinishing();
}
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_input_layout,container,false);
return view;
}
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
Dialog dialog;
dialog = super.onCreateDialog(savedInstanceState);
Window window = dialog.getWindow();
window.setGravity(Gravity.BOTTOM);
return dialog;
}
}
注:此处的R.layout.dialog_input_layout 为自己的弹窗布局,
window.setGravity(Gravity.BOTTON); 表示弹窗显示在底部。?
2 添加弹窗样式R.style.InputDialogStyle;
在res -> values -> themes.xml?(有些版本的文件为styles.xml)?
添加?
<style name="InputDialogStyle" parent="android:Theme.Holo.Light.Dialog">
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowFrame">@null</item>
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowMinWidthMajor">100%</item><!-- 这为最宽100% -->
<item name="android:windowMinWidthMinor">100%</item><!-- 这为最高100% -->
<!-- 设置有遮罩层 -->
<item name="android:backgroundDimEnabled">true</item>
</style>
3.使用方式
弹窗的使用方式为以上部分
下面说的是,当弹窗没被注销,并再次进行show()时,进行重新设置的初始值不变,为上一次show的值,出现这情况就需要重写DialogFragment的 ?onViewStateRestored(),在这里面进行设置初始值
|