有两种方法可以通过DialogFragment
创建自定义对话框。
onCreateDialog
,然后使用AlertDialog.Builder
返回对话框。onCreateView
。我们注意到,如果我们覆盖onCreateDialog
,先前显示的软键盘将不会被隐藏。
但是,如果我们覆盖onCreateView
,则会隐藏先前显示的软键盘。
隐藏软键盘不是我们想要的行为。我们希望软键盘保持原样。
但是,由于提到的限制ViewPager in DialogFragment - IllegalStateException: Fragment does not have a view,我们无法使用onCreateDialog
的方式。简而言之,如果您需要ViewPager
才能在对话框中正常工作,则无法使用onCreateDialog
来实现自定义对话框。
如果使用onCreateView
,除了“不隐藏软键盘”之外,我们可以实现所需的所有功能。
您是否知道为什么覆盖onCreateView
以创建自定义对话框,从而隐藏键盘?我们如何防止这种行为?
我的对话框样式是:
<style name="CustomDialog" parent="@style/Theme.AppCompat.Light.Dialog">
<item name="android:windowNoTitle">false</item>
</style>
ColorDialogFragment.java :
public class ColorDialogFragment extends DialogFragment {
private TabLayout tabLayout;
private ViewPager viewPager;
private ColorFragmentPagerAdapter colorFragmentPagerAdapter;
public static ColorDialogFragment newInstance() {
ColorDialogFragment colorDialogFragment = new ColorDialogFragment();
// We provide custom style, because we need title.
colorDialogFragment.setStyle(DialogFragment.STYLE_NORMAL, R.style.CustomDialog);
return colorDialogFragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onResume() {
super.onResume();
getDialog().getWindow().setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}
private View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container) {
View view = inflater.inflate(R.layout.color_dialog_fragment, container, false);
this.tabLayout = view.findViewById(R.id.tab_layout);
this.viewPager = view.findViewById(R.id.view_pager);
this.colorFragmentPagerAdapter = new ColorFragmentPagerAdapter(this.getChildFragmentManager());
this.viewPager.setAdapter(this.colorFragmentPagerAdapter);
this.tabLayout.setupWithViewPager(this.viewPager);
return view;
}
// We overwrite onCreateView because ViewPager in DialogFragment, can hardly play well with
// onCreateDialog + AlertDialog.Builder.
//
// https://stackoverflow.com/questions/20303865/viewpager-in-dialogfragment-illegalstateexception-fragment-does-not-have-a-vi
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return onCreateView(inflater, container);
}
// We overwrite onCreateDialog, because we need title.
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
dialog.setTitle(R.string.select_a_color);
return dialog;
}
}
答案 0 :(得分:0)
经过一天的实验,我找到了解决方案!
覆盖function DataModel(name) {
this.name = name;
}
DataModel.prototype.logName = function () {
console.log(this.name);
}
module.exports = { DataModel };
和onCreateDialog
。将在onCreateView
创建的视图存储在成员变量中,并让onCreateDialog
返回该成员变量。
参考:https://stackoverflow.com/a/51530917/72437
这是完整的代码。
onCreateView