2011-10-26 54 views
8

我正在嘗試設置保證金以編程方式添加到RadioGroup中單選按鈕,但它失敗:在單選按鈕正確添加,但他們有0保證金...保證金的單選按鈕編程設置不適用

任何人可以幫助?

enter image description here

佈局

<RadioGroup android:id="@+id/rg_nav" android:orientation="vertical" 
    android:layout_width="wrap_content" android:layout_height="wrap_content"> 
</RadioGroup> 

活動

float density = getResources().getDisplayMetrics().density; 

rg_nav = (RadioGroup) findViewById(R.id.rg_nav); 

LinearLayout.LayoutParams params_rb = new LinearLayout.LayoutParams(
     (int)(8*density), 
     (int)(8*density)); 
int margin = (int)(6*density); 
params_rb.setMargins(margin, margin, margin, margin); 

for(String url : product.list_url_pic){ 

    RadioButton radio_btn = new RadioButton(ProductHome.this); 
    radio_btn.setButtonDrawable(R.drawable.rb_nav); 
    radio_btn.setId(rb_id++); 
    rg_nav.addView(radio_btn, params_rb); 
} 

回答

16

我不得不

RadioGroup.LayoutParams params_rb = new RadioGroup.LayoutParams(
       (int)(8*density), 
       (int)(8*density)); 
+0

對於我們單選按鈕的父視圖來說,生成LayoutParams非常重要。謝謝。 – herbertD

+0

什麼是密度? @jul – Erum

+0

@Erum檢查問題,它在那裏定義。 – jul

1

您的代碼似乎是正確的。 嘗試將LayoutParams直接向您的按鈕

radio_btn.setButtonDrawable(R.drawable.rb_nav); 
radio_btn.setId(rb_id++);  
rg_nav.addView(radio_btn); 
radio_btn.setLayoutParams(params_rb); 
+0

同樣的結果.... – jul

+0

@jul嘗試檢查'margin'不是'0':'Log.d(「whatever」,「margin value:」+ margin);' – Vladimir

4

更換

LinearLayout.LayoutParams params_rb = new LinearLayout.LayoutParams(
    (int)(8*density), 
    (int)(8*density)); 

試試這個:

TableRow.LayoutParams rg_params = new TableRow.LayoutParams(0, LayoutParams.WRAP_CONTENT, 3f); 
RadioGroup radio_group=new RadioGroup(this); 
radio_group.setOrientation(RadioGroup.HORIZONTAL); 
radio_group.setLayoutParams(rg_params); 

RadioButton dry=new RadioButton(this); 
RadioGroup.LayoutParams params_soiled = new RadioGroup.LayoutParams(getBaseContext(), null); 
params_soiled.setMargins(10, 0, 10, 0); 
dry.setLayoutParams(button_params);