gpt4 book ai didi

java - Android (Java) : how to use LayoutInflater. 对话框的 inflate()?

转载 作者:行者123 更新时间:2023-11-29 08:24:26 26 4
gpt4 key购买 nike

我在 Dialog 中使用 LayoutInflater 并且不知道要将什么设置为 2nd 参数,即 现在为空

我找到了 answers对于 onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle bundle),但该方法不适用于 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);
}
}

最佳答案

使用这个

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();

关于java - Android (Java) : how to use LayoutInflater. 对话框的 inflate()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54437625/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com