Android(Java):Dialog中如何正确使用LayoutInflater.inflate()?
LayoutInflater.inflate() Null Parameter Error in Custom Dialogs The Problem
You’re building a custom Dialog and using LayoutInflater.inflate() with null as the second parameter, which triggers an Infer error stating the parameter can’t be nullable. You don’t want to pass a fake non-null ViewGroup, and the onCreateView() solution meant for fragments doesn’t apply here.
Your original code had this line causing the issue:
View view = inflater.inflate(R.layout.my_dialog, null);
Infer error message:
MyDialog.java:42: error: ERADICATE_PARAMETER_NOT_NULLABLE
LayoutInflater.inflate(...)需要第二个参数为非空值,但传入的null可能为空。(来源:第42行的null常量)
41. LayoutInflater inflater = LayoutInflater.from(getContext());
42. > View view = inflater.inflate(R.layout.dialog_unlock, null);
The Solution
You don’t need to manually inflate the view at all! The Dialog class has a built-in setContentView(int layoutResID) method that handles the inflation process correctly—including setting up the proper parent container for your layout. This completely avoids the need to deal with the inflater.inflate() call’s second parameter.
Here’s the revised code:
public class MyDialog extends Dialog implements View.OnClickListener { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Let Dialog handle inflation directly with your layout resource setContentView(R.layout.my_dialog); // Now you can find views just like you would in an Activity Button myBtn = findViewById(R.id.my_btn); EditText myTextField = findViewById(R.id.my_et); View.OnClickListener onClickMyBtn = v -> { String value = myTextField.getText().toString(); Log.d("MyDialog", String.format("My value: %s", value)); dismiss(); }; myBtn.setOnClickListener(onClickMyBtn); } }
Why This Works
- The
Dialog'ssetContentView(int)method internally uses aLayoutInflaterwith the correct parent view (the Dialog's own root container), so you don’t have to worry about passing the rightViewGroupparameter. - This approach keeps your code cleaner and aligns with the intended usage of the
Dialogclass. - It eliminates the Infer nullable parameter error entirely, since we’re no longer making the problematic
inflate()call withnull.
内容的提问来源于stack exchange,提问作者Mr. B.

