在Android中以编程方式添加多个文本视图

时间:2013-09-10 07:38:52

标签: android dynamic textview

这里我必须根据数组列表大小以编程方式添加文本视图。文本视图应该像连续模式一样出现在行中... 例如。 tv1,tv2,tv3等等,直到数组列表的大小。

但是我在这里得到的文字视图相互出现。我无法阅读他们的文字。这是我的代码:

ArrayList<String> languageNames = new ArrayList<String>();
RelativeLayout rl = (RelativeLayout)findViewById(R.id.rl);
if(languageNames.size()>0)
{
    int size = languageNames.size();
    TextView[] tv = new TextView[size];
    RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    p.addRule(RelativeLayout.BELOW, tvLocation.getId());

    for(int i=0; i<size; i++)
    {
        tv[i] = new TextView(getBaseContext());
        tv[i].setText(languageNames.get(i).toString());
        tv[i].setLayoutParams(p);
        tv[i].setPadding(50, 50, 0, 0);
        tv[i].setTextColor(Color.parseColor("#000000"));
        rl.addView(tv[i]);
    }
}
else
{

}

需要做什么才能以适当的方式获取文本视图?

2 个答案:

答案 0 :(得分:1)

LinearLayout中添加按钮,并在LinearLayout中添加此RelativeLayout

RelativeLayout r1 = (RelativeLayout) findViewById(R.id.r1);
 RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
p.addRule(RelativeLayout.BELOW, tvLocation.getId());
LinearLayout LL = new LinearLayout(getBaseContext());
LL.setOrientation(LinearLayout.VERTICAL);

   for (int i=0;i< size;i++) {
     tv[i] = new TextView(getBaseContext());
    tv[i].setText(languageNames.get(i).toString());

    tv[i].setPadding(50, 50, 0, 0);
    tv[i].setTextColor(Color.parseColor("#000000"));
     LL.addView(tv);   
 }
r1.addview(LL, p);

答案 1 :(得分:0)

试试这段代码:

LinearLayout rl = (LinearLayout)findViewById(R.id.mainLayout);

    TextView[] tv = new TextView[10];
    for(int i=0; i<10; i++)
    {
        tv[i] = new TextView(getBaseContext());
        tv[i].setText("TextView "+ i);

        tv[i].setPadding(50, 50, 0, 0);
        tv[i].setTextColor(Color.parseColor("#000000"));
        rl.addView(tv[i]);
    }

希望这会对你有所帮助