【问题标题】:Add multiple text views programmatically in Android在 Android 中以编程方式添加多个文本视图
【发布时间】:2019-01-22 17:24:23
【问题描述】:

这里我必须根据数组列表大小以编程方式添加文本视图。文本视图应该像继续模式一样出现在行中...... 例如。 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
{

}

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

【问题讨论】:

  • 你使用 LinearLayout 而不是 RelativeLayout 并将方向设置为 VERTICAL
  • 为 TextViews 设置 id。
  • p.addRule(RelativeLayout.BELOW, tvLocation.getId());将使所有文本视图堆栈在 tvLocation 下方。
  • @Tarun... 我需要 tvLocation 下面的所有文本视图..
  • 用户 LinearLayout 并设置它的方向:垂直它将设置在 textview 下方

标签: android dynamic textview


【解决方案1】:

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

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);

【讨论】:

  • @Tarun...感谢您的回答。在这里,我以垂直方式获取数据......我希望它们像水平模式一样串联......
  • 你可以把LL.setOrientation(LinearLayout.VERTICAL);改成LL.setOrientation(LinearLayout.HORIZONTAL);
  • @Tarun...我得到了输出,但是这里的文本视图的大小与默认的文本视图不同。如何将它们设置为默认大小?
【解决方案2】:

试试这个代码:

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]);
    }

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2011-03-13
    • 2023-03-20
    • 2012-05-26
    • 1970-01-01
    • 1970-01-01
    • 2015-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多