以编程方式构建xml相对布局

时间:2013-04-24 12:51:06

标签: android xml relativelayout

我正在尝试在运行时更新/填充xml。 textViews显示正常,但似乎在第一个项目之后无法正确定位它们(​​请参阅else语句)。是因为getId()未被承认还是我完全错了?

for(int x=1; x<13; x++){
    String prompt="PROMPT_"+String.valueOf(x);
    String promptValue = myTacorCursor.getString(myTacorCursor.getColumnIndex(prompt));
    //if not empty draw a row
    if (!promptValue.equals("")){
        //insert new rows into layout
        RelativeLayout myLayout = (RelativeLayout) findViewById(R.id.RelativeLayout1);
        TextView promptLabel = new TextView(this);
        promptLabel.setTextAppearance(this, android.R.style.TextAppearance_DeviceDefault_Large);
        promptLabel.setText(myTacorCursor.getString(myTacorCursor.getColumnIndex("PROMPT_"+String.valueOf(x))));                
        promptLabel.setId(1);
        ((RelativeLayout) myLayout).addView(promptLabel);

        RelativeLayout.LayoutParams mLayoutParams1=(RelativeLayout.LayoutParams)promptLabel.getLayoutParams();
        mLayoutParams1.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        if (i==1){
            mLayoutParams1.addRule(RelativeLayout.BELOW,R.id.textView7);
            Log.w("ID is:", String.valueOf(promptLabel.getId()));
        } else{                 
            mLayoutParams1.addRule(RelativeLayout.BELOW,promptLabel.getId());
            Log.w("ID is:", String.valueOf(promptLabel.getId()));
        }
    i++;
    }
}   

我正在尝试显示:

(textView)LABEL xx R.id.textview7
<-- here would be the inserted columns -->
(text view) prompt 1 
(text view) prompt 2
(text view) prompt 3
... etc ...'

2 个答案:

答案 0 :(得分:1)

动态设置ID即可。只需要一些注意力和你的代码。

  1. 至于你在for循环中,最好只在一个地方增加索引。
  2. 更改LayoutParams的{​​{1}}后,您需要将其设置回来:View
  3. 试试这个。它应该工作:

    promptLabel.setLayoutParams(layoutParams)

答案 1 :(得分:0)

您无需以编程方式构建整个布局。在单独的布局xml文件中定义它,然后使用布局inflater对其进行充气。之后,将其添加到您想要的位置。

我从未见过以编程方式分配的id,但根据我的建议,您可以像往常一样在xml中定义它们。

PS:Here是一个很好的例子,解释了如何使用LayoutInflater