0

我希望能够让用户选择选项,并希望在对话框中提供一些单选按钮。我已经在 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);

我究竟做错了什么?

4

2 回答 2

1

当您想要获取位于对话框中的 UI 元素的 ID 时,您需要这样做。

  Dialog dialog = new Dialog(mContext); // your dialog creation method here
  RadioButton radio_date = (RadioButton) dialog.findViewById(R.id.RBdate);

如果您使用findViewById,那么您正在尝试捕获与当前活动视图关联的视图对象(您将在setContentViewAPI 中设置)

因此,它试图在活动视图中查找具有 idRBdate的视图,但它无法找到并因此返回 null。

于 2012-02-24T10:59:41.890 回答
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();
        }
    });

你试试这个,让我知道

于 2012-02-24T10:59:04.470 回答