所以我正在使用AlertDialog显示我的RadioGroup,并且我想获取RadioButton的值以传递给我的下一个方法。但是,当我运行程序时,它将返回错误:
java.lang.NullPointerException:尝试调用虚拟方法'int 空对象上的android.widget.RadioGroup.getCheckedRadioButtonId()' 参考
我该如何解决?
private void showChoosePackage() {
AlertDialog.Builder builder = new AlertDialog.Builder(descriptionsActivity.this);
LayoutInflater inflater = this.getLayoutInflater();
View choose_package_layout = inflater.inflate(R.layout.choose_package_layout, null);
builder.setView(choose_package_layout);
final AlertDialog dialog = builder.create();
radioGroup = findViewById(R.id.radio_grp);
Button btnApply = choose_package_layout.findViewById(R.id.button_apply);
final RadioButton rdibtn = (RadioButton)choose_package_layout.findViewById(R.id.radio1);
final RadioButton rdibtn2 = (RadioButton)choose_package_layout.findViewById(R.id.radio2);
rdibtn.setText(Common.longhousedesc.PackageOne);
rdibtn2.setText(Common.longhousedesc.PackageTwo);
btnApply.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int Selectedid = radioGroup.getCheckedRadioButtonId();
radioButton = findViewById(Selectedid);
showConfirmDialog(radioButton.getText());
}
});
builder.show();
}
答案 0 :(得分:0)
找到广播组时需要指定视图:
radioGroup = choose_package_layout.findViewById(R.id.radio_grp);
答案 1 :(得分:0)
findViewById
需要上下文才能找到视图。由于您是在对话框中调用它,因此需要在其视图中找到该视图。
private void showChoosePackage() {
AlertDialog.Builder builder = new AlertDialog.Builder(descriptionsActivity.this);
LayoutInflater inflater = this.getLayoutInflater();
final View choose_package_layout = inflater.inflate(R.layout.choose_package_layout, null);
builder.setView(choose_package_layout);
final AlertDialog dialog = builder.create();
final RadioGroup radioGroup = findViewById(R.id.radio_grp);
Button btnApply = choose_package_layout.findViewById(R.id.button_apply);
final RadioButton rdibtn = (RadioButton)choose_package_layout.findViewById(R.id.radio1);
final RadioButton rdibtn2 = (RadioButton)choose_package_layout.findViewById(R.id.radio2);
rdibtn.setText(Common.longhousedesc.PackageOne);
rdibtn2.setText(Common.longhousedesc.PackageTwo);
btnApply.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int Selectedid = radioGroup.getCheckedRadioButtonId();
radioButton = choose_package_layout.findViewById(Selectedid);
showConfirmDialog(radioButton.getText());
}
});
dialog.show();
}