【问题标题】:DialogFragment onCreateView not returning custom layout view?DialogFragment onCreateView 不返回自定义布局视图?
【发布时间】:2017-05-23 09:27:42
【问题描述】:

我目前正在尝试对我的 DialogFragment 使用自定义布局,但似乎我做错了什么。这是我的班级目前的样子:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    setRetainInstance(true);
    Log.d(TAG, "onCreateDialog");
    return new AlertDialog.Builder(getActivity())
            .setPositiveButton(android.R.string.ok, passDataListener)
            .setNegativeButton(android.R.string.cancel, null)
            .setCancelable(true)
            .create();
}

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    Log.d(TAG, "onCreateView");
    setTitleFromBundle();
    return inflater.inflate(R.layout.dialog_edittext, container);


}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    mEditText = (EditText) view.findViewById(R.id.dialog_edittext);
    tvUnits = (TextView) view.findViewById(R.id.dialog_units);

    setMaxCharsFromBundle();
    setTextFromBundle();
    setHintFromBundle();
    setInputTypeFromBundle();
    setUnitsTextViewFromBundle();
}

正面/负面按钮显示(连同标题)但是,我的布局没有。

【问题讨论】:

  • 如果您使用对话框片段,那么为什么在 OnCreate 中使用 AlertDialog.Builder?

标签: android android-fragments dialogfragment


【解决方案1】:

不需要覆盖onCreateView()

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
setRetainInstance(true);
Log.d(TAG, "onCreateDialog");
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
return new AlertDialog.Builder(getActivity())
        .setView(inflater.inflate(R.layout.dialog_edittext, null))
        .setPositiveButton(android.R.string.ok, passDataListener)
        .setNegativeButton(android.R.string.cancel, null)
        .setCancelable(true)
        .create();
}

【讨论】:

    【解决方案2】:

    您不能同时使用onCreateDialogonCreateView 这两种方法。您必须选择是否要显示“基本对话框”然后覆盖onCreateDialog。如果要显示“自定义对话框”,请覆盖 onCreateView。请注意,您也可以覆盖onCreateDialog 并使用youralertdialog.setView() 设置自己的布局。

    【讨论】:

      【解决方案3】:

      您应该只实现onCreateViewonCreateDialog 之间的一种方法,而不是两者。

      • onCreateView : 提供对话框的内容
      • onCreateDialog :创建一个完全自定义的对话框,例如 AlertDialog,并带有自己的内容

      文档here中描述了所有内容

      如需完整指南,您可以查看https://guides.codepath.com/android/Using-DialogFragment

      【讨论】:

        猜你喜欢
        • 2012-10-26
        • 1970-01-01
        • 1970-01-01
        • 2016-01-21
        • 1970-01-01
        • 1970-01-01
        • 2016-04-01
        • 2013-04-27
        • 1970-01-01
        相关资源
        最近更新 更多