我有一个包含单选按钮的自定义对话框,但是当我添加一个oncheckedchangelistener时,我的应用程序崩溃了。可能是什么问题?
提前致谢! :d
这是我的代码:
--jars
这是错误跟踪:
GridViewAdapter adapter = new GridViewAdapter(alcoholType.this, images,names);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.alcoholdialog);
dialog.setTitle("ORDER " + names.get(position));
radioQuantity = (RadioGroup) findViewById(R.id.radioQuantity);
quantity1 = (RadioButton) findViewById(R.id.quantity1);
quantity2 = (RadioButton) findViewById(R.id.quantity2);
radioQuantity.clearCheck();
radioQuantity.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
}
});
dialog.show();
}
});
答案 0 :(得分:3)
您需要使用Dialog's
引用来获取视图:
使用:
radioQuantity = (RadioGroup) dialog.findViewById(R.id.radioQuantity);
quantity1 = (RadioButton) dialog.findViewById(R.id.quantity1);
quantity2 = (RadioButton) dialog.findViewById(R.id.quantity2);
由于您的NullPointerException
未附加到视图,因此您获得RadioGroup
。
同样适用于CheckedListener
:
radioQuantity.setOnCheckedChangeListener(new
RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.quantity1) {
//Your code
} else if (checkedId == R.id.quantity2) {
//Your code
}
}
});
答案 1 :(得分:2)
请尝试以下代码
radioQuantity = (RadioGroup) dialog.findViewById(R.id.radioQuantity);
quantity1 = (RadioButton) dialog.findViewById(R.id.quantity1);
quantity2 = (RadioButton) dialog.findViewById(R.id.quantity2);
radioQuantity.setOnCheckedChangeListener(new
RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.quantity1) {
Log.d("radiobox", "clickingevent");
optionans = "1";
} else if (checkedId == R.id.quantity2) {
optionans = "2";
}
}
});