单选按钮与右侧文本和左侧按钮对齐

时间:2012-11-26 01:09:06

标签: java android android-layout relativelayout

我正在尝试以编程方式对齐左侧的radiobutton文本和右侧的按钮,而不是下一个屏幕截图中显示的内容

normal radiobtns

我尝试在dinamically中创建RelativeLayout并放置textview和radiobtn(没有文本),但每次尝试都不成功:(

我在这里发布了我试图运行但无法对齐的代码。

        RelativeLayout relLay = new RelativeLayout(this);
        relLay.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

        TextView textView=new TextView(this);
        textView.setText(device.getName());
        textView.setGravity(Gravity.LEFT);  

        RadioButton radioBtn= new RadioButton(this);
        radioBtn.setText(" ");
        radioBtn.setTag(device);
        radioBtn.setChecked(false);
        radioBtn.setGravity(Gravity.RIGHT); 

        RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

        lp1.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
        RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

        lp2.addRule(RelativeLayout.ALIGN_PARENT_RIGHT,RelativeLayout.TRUE);

        relLay.addView(textView,lp1);
        relLay.addView(radioBtn,lp2);
        radioGr.addView(relLay);

我还要注意,我在一个放射线组中添加了相对布局,它是由ScrollView包含的。

提前感谢您的帮助和耐心

1 个答案:

答案 0 :(得分:0)

您可以使用以下代码:

RelativeLayout relLay = new RelativeLayout(this);
            relLay.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
            relLay.setGravity(Gravity.RIGHT);
            TextView textView=new TextView(this);
            textView.setText("good");
            textView.setGravity(Gravity.RIGHT);  
            RadioButton radioBtn= new RadioButton(this);
            radioBtn.setChecked(false);
            radioBtn.setId(125); //you must setid for radioBtn

            RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

          lp1.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
            RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(
                 RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            lp1.addRule(RelativeLayout.ALIGN_BASELINE,radioBtn.getId());
          lp1.addRule(RelativeLayout.LEFT_OF,radioBtn.getId());
            lp2.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
            relLay.addView(radioBtn,lp2);
            relLay.addView(textView,lp1);
            this.setContentView(relLay);