动态单选按钮布局不起作用

时间:2012-07-18 19:50:30

标签: android layout

我正在尝试将动态单选按钮设置为线性布局。我有两个单选按钮,从List调用并添加到Linear Layout。一切正常,直到我看到我的单选按钮看起来很糟糕,并坚持这个布局。我的问题是为什么我的单选按钮布局根本不起作用?
这是我的代码:

TextView label;
RadioButton[] rb;
RadioGroup radiogroup;
LinearLayout ll;
String title;

public MyBtn(Context context,String labelText,String options) {
   super(context);

   ll = new LinearLayout(context);
   ll.setOrientation(LinearLayout.VERTICAL);

   LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
       LayoutParams.FILL_PARENT,
       LayoutParams.WRAP_CONTENT);

   ll.setLayoutParams(params);

   label = new TextView(context);
   label.setText(labelText);
   label.setTextColor(getResources().getColor(R.color.label_color));

   radiogroup = new RadioGroup(context);
   radiogroup.setOrientation(RadioGroup.HORIZONTAL);

   radiogroup.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

   LinearLayout.LayoutParams [] rbLayout = new RadioGroup.LayoutParams[2]; 

   LinearLayout.LayoutParams  rbParam = new RadioGroup.LayoutParams(
         RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT);
   rbParam.weight = 1f;
   rbParam.gravity = Gravity.CENTER | Gravity.LEFT;

   LinearLayout.LayoutParams  rbParam2 = new RadioGroup.LayoutParams(
         RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT);
   rbParam2.gravity = Gravity.CENTER | Gravity.RIGHT;
   rbParam2.weight = 1f;

   rbLayout[0] = new RadioGroup.LayoutParams(rbParam);                  
   rbLayout[1] = new RadioGroup.LayoutParams(rbParam2);

   List<String> list = Arrays.asList(options.split("\\|"));
   String[] opts = new String[list.size()];
   list.toArray(opts);

   rb = new RadioButton[list.size()];

   for (int i = 0; i < list.size(); i++) {
      rb[i] = new RadioButton(context);
      rb[i].setText(opts[i]);
      rb[i].setId(i);
      radiogroup.addView(rb[i],rbLayout[i]);         
   }

   title = label.getText().toString();

   radiogroup.check(0);

   ll.addView(label);
   ll.addView(radiogroup);

   //int resID = getResources().getIdentifier(buttonID, "id", context.getPackageName());  

   this.addView(ll); 
}

谢谢。

我的单选按钮:
image link

它应该:
image link

1 个答案:

答案 0 :(得分:0)

改变这个:

LinearLayout.LayoutParams [] rbLayout = new RadioGroup.LayoutParams[2];
LinearLayout.LayoutParams  rbParam2 = new RadioGroup.LayoutParams(
     RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT);

到此:

RadioGroup.LayoutParams [] rbLayout = new RadioGroup.LayoutParams[2];
RadioGroup.LayoutParams  rbParam2 = new RadioGroup.LayoutParams(
     RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT);

您的代码中存在许多相同的错误。找出它们并纠正 让我知道结果


LinearLayout.LayoutParams  rbParam = new RadioGroup.LayoutParams(
     RadioGroup.LayoutParams.FILL_PARENT, RadioGroup.LayoutParams.WRAP_CONTENT,1f);

必须有效。 让我知道它