0

我对 android 很陌生,并尝试使用没有 xml 的 android api 水平放置元素。

我想要做的是水平放置 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都在重叠。我在哪里犯错误?

提前致谢。

4

1 回答 1

1

您不能期望RelativeLayout相对于它不包含的其他视图放置视图。RelativeLayout不了解 的 ID,因为RadioButtons它们尚未添加到其中。因此,除了(只是 a )RadioButton之外的任何其他布局中添加的a都不会具有您在用户点击它们进行检查时可能正在寻找的互斥逻辑。RadioGroupLinearLayout

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每行使用的项目高度。您可以看到在纯 Java 中进行布局非常冗长,这就是首选方法是 XML 的原因。

于 2013-02-05T04:00:00.863 回答