RadioGroup動態添加RadioButton,並且獲得事件

由於有許多的RadioButton是動態的,不是固定的一些,所以需要在代碼中,動態的添加到RadioGroup中,下面是我的實現方法。


1、添加RadioButton到RadioGroup中

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);
}



2、爲RadioGroup添加事件處理,可以得到當前選擇的RadioButton

        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進行處理了
            }
        });


發佈了36 篇原創文章 · 獲贊 4 · 訪問量 48萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章