我正在尝试通过使用生成器并设置自定义 View 来创建AlertDialog。当我尝试在onCreateDialog内填充 View 时,出现StackOverflowError。

这是直到循环回到onCreateDialog的代码:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState){
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle(R.string.enter_time);

    LinearLayout outerLayout = (LinearLayout) getLayoutInflater(savedInstanceState)
            .inflate(R.layout.time_entry_dialog, null);
    ...
}

这是LogCat的输出:
02-28 22:30:04.220: E/AndroidRuntime(4250): FATAL EXCEPTION: main
02-28 22:30:04.220: E/AndroidRuntime(4250): java.lang.StackOverflowError
02-28 22:30:04.220: E/AndroidRuntime(4250):     at android.app.Activity.getSystemService(Activity.java:4009)
02-28 22:30:04.220: E/AndroidRuntime(4250):     at android.view.LayoutInflater.from(LayoutInflater.java:210)
02-28 22:30:04.220: E/AndroidRuntime(4250):     at android.view.ContextThemeWrapper.getSystemService(ContextThemeWrapper.java:75)
02-28 22:30:04.220: E/AndroidRuntime(4250):     at com.android.internal.app.AlertController$AlertParams.<init>(AlertController.java:812)
02-28 22:30:04.220: E/AndroidRuntime(4250):     at android.app.AlertDialog$Builder.<init>(AlertDialog.java:374)
02-28 22:30:04.220: E/AndroidRuntime(4250):     at android.app.AlertDialog$Builder.<init>(AlertDialog.java:359)
02-28 22:30:04.220: E/AndroidRuntime(4250):     at com.sweatyreptile.chee.runtimetracker.TimeEntryDialogFragment.onCreateDialog(TimeEntryDialogFragment.java:18)
02-28 22:30:04.220: E/AndroidRuntime(4250):     at android.support.v4.app.DialogFragment.getLayoutInflater(DialogFragment.java:295)
02-28 22:30:04.220: E/AndroidRuntime(4250):     at com.sweatyreptile.chee.runtimetracker.TimeEntryDialogFragment.onCreateDialog(TimeEntryDialogFragment.java:21)
02-28 22:30:04.220: E/AndroidRuntime(4250):     at android.support.v4.app.DialogFragment.getLayoutInflater(DialogFragment.java:295)
02-28 22:30:04.220: E/AndroidRuntime(4250):     at com.sweatyreptile.chee.runtimetracker.TimeEntryDialogFragment.onCreateDialog(TimeEntryDialogFragment.java:21)
02-28 22:30:04.220: E/AndroidRuntime(4250):     at android.support.v4.app.DialogFragment.getLayoutInflater(DialogFragment.java:295)
...etc

编辑:我在DialogFragment.getLayoutInflater()的源代码中找到了这一行:
mDialog = onCreateDialog(savedInstanceState);

所以..如果在不引起无限递归的情况下无法在onCreateDialog内获取LayoutInflator,如何为自定义AlertDialog填充 View ?

最佳答案

如果发现问题。 DialogFragment.getLayoutInflater()包含对onCreateDialog()的调用,因此从onCreateDialog()中调用getLayoutInflater()会创建一个无限循环。

我在以下答案中找到了解决方案:https://stackoverflow.com/a/10585164/2020340

我不确定这是否是一种好的形式,因为它看起来并不是真的,但是我将其替换

getLayoutInflater(savedInstanceState)


getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

编辑:它们是相同的。有关详细信息,请参见此答案:https://stackoverflow.com/a/20995083/2020340

07-24 14:01