我希望能够让用户选择一个选项,并希望在对话框中关闭一些单选按钮。我在OnCreate部分
中声明了这样的单选按钮@Override
protected Dialog onCreateDialog(int id) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
if (id > 0)
{
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View layout = layoutInflater.inflate(R.layout.lectsort_dialog, (ViewGroup) findViewById(R.id.lect_sort));
builder.setView(layout);
// Now configure the AlertDialog
builder.setTitle(R.string.exsort_title);
radio_date = (RadioButton) findViewById(R.id.RBdate);
radio_loctn = (RadioButton) findViewById(R.id.RBloctn);
radio_stream = (RadioButton) findViewById(R.id.RBstream);
radio_date.setOnClickListener(radio_listener);
radio_loctn.setOnClickListener(radio_listener);
radio_stream.setOnClickListener(radio_listener);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
}
radio_listener过程声明如下
RadioButton.OnClickListener radio_listener =
new RadioButton.OnClickListener()
{
@Override
public void onClick(View v) {
// Perform action on clicks
RadioButton rb = (RadioButton) v;
Toast.makeText(LecturesActivity.this, rb.getText(), Toast.LENGTH_SHORT).show();
}
};
但是,当调用该对话框时,我在此行上出现Null异常错误
radio_date.setOnClickListener(radio_listener);
我做错了什么?
答案 0 :(得分:1)
当您想要获取位于对话框中的UI元素的ID时,您需要这样做。
Dialog dialog = new Dialog(mContext); // your dialog creation method here
RadioButton radio_date = (RadioButton) dialog.findViewById(R.id.RBdate);
如果您使用findViewById
,那么您正在尝试捕获与当前活动视图关联的视图对象(您将在setContentView
API中设置)
因此,它试图在活动视图中找到一个ID为RBdate
且无法找到的视图,因此返回null。
答案 1 :(得分:0)
检查以下代码 这是一个单击按钮
时带有单选按钮的警报final AlertDialog.Builder builder = new AlertDialog.Builder(this);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
//int states = {false, false};
builder.setTitle("Select the item that you want to delete from that item ");
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// TODO Auto-generated method stub
if(id==0){
}
else
{
});
alert= builder.create();
alert.show();
}
});
你试试这个让我知道