Android:动态添加textView。如何将其添加到特定行

时间:2011-12-23 11:07:53

标签: android background textview line stretched

我有5个文本视图,这些视图被添加到dinamicly但每个textViews覆盖其他文本视图。如何将每个textView添加到特定行?

for(int z=0;z<c;z++){
    TextView lastHour = new TextView(projectActivity.this);
    lastHour.setPadding(5,z*35,0,0); // it currently allows me to see each textView in other line
    lastHour.setText("text"+z);                 
    relative_layout_for_last.addView(lastHour);
}

当我使用setPadding时,textView的背景被拉伸。 我只想在除以前的textViews之外的其他行中添加每个textView。

4 个答案:

答案 0 :(得分:2)

LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
             50, (LayoutParams.WRAP_CONTENT));
        lp.leftMargin=5;
or(int z=0;z<c;z++){
    TextView lastHour = new TextView(projectActivity.this);
    lastHour.setPadding(5,z*35,0,0); // it currently allows me to see each textView in other line
    lastHour.setText("text"+z);    
    lastHour.setLayoutParams(lp);             
    relative_layout_for_last.addView(lastHour);
}
像这样,您可以像在XML中一样添加自己的布局参数,并在视图中大致设置文本视图。

答案 1 :(得分:1)

您可以将它们包裹在线性布局中,并将方向设置为垂直。

http://developer.android.com/reference/android/widget/LinearLayout.html

如果您需要任何代码段,请询问。我在这里有点匆忙;)

答案 2 :(得分:0)

填充不会做你想要的。它只会增加顶部和内容之间的空间。将它们添加到具有垂直方向的LinearLayout,如Bram所说,或者如果您愿意保留RelativeLayout,请添加一个layout_below约束,指定顶部视图的ID。

答案 3 :(得分:0)

您应该使用LinearLayout围绕TextViews。布局的方向应为vertical

如果你需要坚持RelativeLayout,你应该加上:

layoutParams.addRule(RelativeLayout.BELOW, theTextViewAbove.getId());