You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android(Java):Dialog中如何正确使用LayoutInflater.inflate()?

Fixing the 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's setContentView(int) method internally uses a LayoutInflater with the correct parent view (the Dialog's own root container), so you don’t have to worry about passing the right ViewGroup parameter.
  • This approach keeps your code cleaner and aligns with the intended usage of the Dialog class.
  • It eliminates the Infer nullable parameter error entirely, since we’re no longer making the problematic inflate() call with null.

内容的提问来源于stack exchange,提问作者Mr. B.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:20:03