Android以编程方式向TableRow添加多个TextView [英] Android Adding more than one TextView to a TableRow Programmatically

查看:400
本文介绍了Android以编程方式向TableRow添加多个TextView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在FrameLayout中有一个LinearLayout,用于制表符.而且我正在尝试在代码中将TableRow添加到LinearLayout.

I have a LinearLayout inside a FrameLayout for tab purposes. And I'm trying to add TableRow's to the LinearLayout in the code.

LinearLayout testLayout = (LinearLayout)findViewById(R.id.testLayout);
TableRow tableRow = new TableRow(this);
tableRow.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));

这将获取我的LinearLayout并创建一个符合我想要的规格的TableRow.我知道这部分正在工作.

This gets my LinearLayout and creates a TableRow to the specifications I want. I know this part is working.

TextView textOne = new TextView(this);
textOne.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
textOne.setText("One");

TextView textTwo = new TextView(this);
textTwo.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
textTwo.setText("Two");

在这里,我可以毫无问题地制作两个TextViews.

Here I make my two TextViews with no problem.

tableRow.addView(textOne);
tableRow.addView(textTwo);
testLayout.addView(tableRow, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));

在这里,我认为一切都出错了.发生的事情是只显示textTwo.我不知道为什么它没有像XML中的正常TableRow那样按顺序显示它们.我再说一遍,这必须用代码完成. 请帮忙,谢谢.

Here is where I assume everything goes wrong. What happens is it only shows the textTwo. I don't know why it's not showing both of them in order like a normal TableRow would in XML. And I repeat, this must be done in code. Please help, thank you.

推荐答案

我认为您想动态创建TextView,并且应该收到错误消息"removeView()parent".这是一个很好的解决方案:

I think you want to create your TextView dynamically and should're getting error "removeView () parent." Here is a good solution for that:

TableView tlSkills = (TableView) findViewById(R.id.myTableView);
if(listSkills.size() > 0) {
     TableRow tableRow = new TableRow(getContext());

     int i = 0;
     for (Skills s : listSkills) {
     TextView textView = new TextView(getContext());
     textView.setText("" + s.getName());

     tableRow.addView(textView);

     if(i > 0) { 
          tlSkills.removeView(tableRow);//this is to avoid the error I mentioned above.
     }

     tlSkills.addView(tableRow);

     i++;
  }
}

这篇关于Android以编程方式向TableRow添加多个TextView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆