我在LayoutInflater
中使用Dialog
,但不知道将什么设置为 2nd 参数,目前为null
。
我为onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle bundle)
找到了answers,但该方法不适用于Dialog
。
用null
之类的东西使(ViewGroup) null
变色对我来说是一个选项。
MyDialog
public class MyDialog extends Dialog implements View.OnClickListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater inflater = LayoutInflater.from(getContext());
View view = inflater.inflate(R.layout.my_dialog, null);
// ________________ How to replace that null? ___________________^
setContentView(view);
}
}
由Infer报告的错误:
MyDialog.java:42: error: ERADICATE_PARAMETER_NOT_NULLABLE
`LayoutInflater.inflate(...)` needs a non-null value in parameter 2 but argument `null` can be null. (Origin: null constant at line 42).
41. LayoutInflater inflater = LayoutInflater.from(getContext());
42. > View view = inflater.inflate(R.layout.dialog_unlock, null);
有什么想法吗?预先感谢!
解决方案
public class MyDialog extends Dialog implements View.OnClickListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_dialog);
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);
}
}
答案 0 :(得分:4)
使用此
setContentView(R.layout.my_dialog);
代替这个
LayoutInflater inflater = LayoutInflater.from(getContext());
View view = inflater.inflate(R.layout.my_dialog, null);
setContentView(view);
示例代码
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MyDialog extends Dialog implements View.OnClickListener {
public MyDialog(Context context) {
super(context);
}
Button myBtn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_dialog);
myBtn = findViewById(R.id.my_btn);
myBtn.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if (view == myBtn) {
Toast.makeText(view.getContext(), "clicked", Toast.LENGTH_SHORT).show();
}
}
}
然后像这样创建对话框
MyDialog myDialog = new MyDialog(this);
myDialog.show();