因爲有許多的RadioButton是動態的,不是固定的一些,因此須要在代碼中,動態的添加到RadioGroup中,下面是個人實現方法。 java
一、添加RadioButton到RadioGroup中 ide
- RadioGroup group;
- for(int i=0; i<10; i++)
- {
- RadioButton tempButton = new RadioButton(this);
- tempButton.setBackgroundResource(R.drawable.xxx); // 設置RadioButton的背景圖片
- tempButton.setButtonDrawable(R.drawable.xxx); // 設置按鈕的樣式
- tempButton.setPadding(80, 0, 0, 0); // 設置文字距離按鈕四周的距離
- tempButton.setText("按鈕 " + i);
- group.addView(tempButton, LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
- }
二、爲RadioGroup添加事件處理,能夠獲得當前選擇的RadioButton this
- group.setOnCheckedChangeListener(new OnCheckedChangeListener() {
-
- @Override
- public void onCheckedChanged(RadioGroup group, int checkedId) {
- // TODO Auto-generated method stub
- RadioButton tempButton = (RadioButton)findViewById(checkedId); // 經過RadioGroup的findViewById方法,找到ID爲checkedID的RadioButton
- // 如下就能夠對這個RadioButton進行處理了
- }
- });