在android中线性放置元素

时间:2013-02-05 02:30:55

标签: android android-layout

我对android很新,并试图使用没有xml的android apis水平放置元素。

我要做的是水平放置RadioButtons和EditText。类似的东西:

R-----E
R-----E

我尝试了这样的代码:

RadioGroup rg = new RadioGroup(this); //create the RadioGroup
rg.setOrientation(RadioGroup.VERTICAL);//or RadioGroup.VERTICAL
for(Map.Entry<String,String> entry : storedCards.entrySet())
{
    RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(
        RelativeLayout.LayoutParams.WRAP_CONTENT,
        RelativeLayout.LayoutParams.WRAP_CONTENT);
    EditText ed = new EditText(this);
    RadioButton rb  = new RadioButton(this);
    rb.setId(counter++);

    lp2.addRule(RelativeLayout.RIGHT_OF,rb.getId());
    ed.setLayoutParams(lp2);

    rg.addView(rb); //the RadioButtons are added to the radioGroup instead of the layout
    rb.setText(entry.getKey());
    relativeLayout.addView(ed);
}

这不起作用。但这就是我要做的事情:首先我使用counter变量为每个单选按钮设置id,并尝试使用以下方法在该单选按钮的右侧站点上设置edittext视图:

lp2.addRule(RelativeLayout.RIGHT_OF,rb.getId());

但我没有得到正确的结果。我只是这样:

ER
R

所有EditText都在重叠。我在哪里弄错了?

提前致谢。

1 个答案:

答案 0 :(得分:1)

您不能指望RelativeLayout相对于其不包含的其他视图放置视图。 RelativeLayout无法理解RadioButtons的ID,因为它们尚未添加到RadioButton中。因此,添加到除RadioGroup(仅为LinearLayout)之外的任何其他布局的RadioButton将不具有您在用户点按它们时可能要查找的互斥逻辑检查。

因此,您必须在垂直RadioGroup中展示EditText个项目,让LinearLayout个项目排在他们旁边的最简单方法是创建第二个LinearLayout root = new LinearLayout(this); root.setOrientation(LinearLayout.HORIZONTAL); RadioGroup buttonGroup = new RadioGroup(this); buttonGroup.setOrientation(RadioGroup.VERTICAL); LinearLayout editLayout = new LinearLayout(this); editLayout.setOrientation(LinearLayout.VERTICAL); //Add left/right pane to root layout LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); root.addView(buttonGroup, lp); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT); root.addView(editLayout, lp); //Fixed height for each row item (45dp in this case) //Getting DP values in Java code is really ugly, which is why we use XML for this stuff int rowHeightDp = (int)TypedValue.applyDimension(COMPLEX_UNIT_DIP, 45.0f, getResources.getDisplayMetrics()); for(Map.Entry<String,String> entry : storedCards.entrySet()) { EditText ed = new EditText(this); RadioButton rb = new RadioButton(this); rb.setId(counter++); rb.setText(entry.getKey()); //Add each item with its LayoutParams LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, rowHeightDp) ); buttonGroup.addView(rb, lp1); lp1 = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, rowHeightDp) ); editLayout.addView(ed, lp1); } 它旁边,并使用固定高度来确保每个“行”匹配。类似的东西:

LayoutParams

这会创建两个并排布局,由于固定的项目高度而保持排列。您可以在每行使用的{{1}}中调整项目高度。您可以看到纯Java中的布局如何非常冗长,这就是首选方法是XML的原因。