2012-02-23 34 views
0

我有一個Android應用程序,我想向用戶提供使用不同字段排序表的選擇。我使用了一個帶有三個單選按鈕的對話框來提供每種排序類型的選擇。在Android應用程序的對話框中使用單選按鈕

下面的對話框代碼中的代碼聲明單選按鈕

 LayoutInflater layoutInflater = (LayoutInflater) 
     getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     final View layout = layoutInflater.inflate(R.layout.lectindex_dialog, (ViewGroup) findViewById(R.id.lect_index)); 

     builder.setView(layout); 

     // Now configure the AlertDialog 
     builder.setTitle(R.string.exindex_title);      

     final RadioButton radio_date = (RadioButton) findViewById(R.id.RBdate); 
     final RadioButton radio_loctn = (RadioButton) findViewById(R.id.RBloctn); 
     final RadioButton radio_stream = (RadioButton) findViewById(R.id.RBstream);   
     radio_date.setOnClickListener(radio_listener); 
     radio_loctn.setOnClickListener(radio_listener); 
     radio_stream.setOnClickListener(radio_listener); 

     builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int whichButton) { 
       // We forcefully dismiss and remove the Dialog, so it cannot be used again (no cached info) 
       LecturesActivity.this.removeDialog(SELINDEX_DIALOG_ID); 
      } 
     }); 

爲radio_listener的代碼另行申報,像這樣

 private OnClickListener radio_listener = new OnClickListener() { 
      public void onClick(View v) { 
      // Perform action on clicks 
      RadioButton rb = (RadioButton) v; 
      Toast.makeText(LecturesActivity.this, rb.getText(), Toast.LENGTH_SHORT).show(); 
      } 
     }; 

一切似乎工作確定,但對於radio_listener代碼永遠不會被使用,爲什麼?

回答

0

錯誤和radio_listener永遠不會被調用的原因是它在嘗試使用radio_date時會引發錯誤,因爲它沒有正確聲明。當我將聲明更改爲最終RadioButton radio_date =(RadioButton)layout.findViewById(R.id.RBdate); 其中佈局是對話框的代碼,代碼完美工作。

0

您是否嘗試過使用RadioGroup而不是單獨的單選按鈕?您將更少地控制自己的行爲IMO

相關問題