RadioGroup動態添加RadioButton,而且得到事件

因爲有許多的RadioButton是動態的,不是固定的一些,因此須要在代碼中,動態的添加到RadioGroup中,下面是個人實現方法。 java


一、添加RadioButton到RadioGroup中 ide

[java]  view plain copy
  1. RadioGroup group;  
  2. for(int i=0; i<10; i++)  
  3. {  
  4.     RadioButton tempButton = new RadioButton(this);  
  5.     tempButton.setBackgroundResource(R.drawable.xxx);   // 設置RadioButton的背景圖片  
  6.     tempButton.setButtonDrawable(R.drawable.xxx);           // 設置按鈕的樣式  
  7.     tempButton.setPadding(80000);                 // 設置文字距離按鈕四周的距離   
  8.     tempButton.setText("按鈕 " + i);  
  9.     group.addView(tempButton, LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);  
  10. }  



二、爲RadioGroup添加事件處理,能夠獲得當前選擇的RadioButton this

[java]  view plain copy
  1. group.setOnCheckedChangeListener(new OnCheckedChangeListener() {  
  2.       
  3.     @Override  
  4.     public void onCheckedChanged(RadioGroup group, int checkedId) {  
  5.         // TODO Auto-generated method stub  
  6.         RadioButton tempButton = (RadioButton)findViewById(checkedId); // 經過RadioGroup的findViewById方法,找到ID爲checkedID的RadioButton  
  7.         // 如下就能夠對這個RadioButton進行處理了  
  8.     }  
  9. });  
相關文章
相關標籤/搜索