android: two issues using Tablerow+TextView in Tablelayout
我正在使用Tablerow + TextView对博客帖子及其回复进行简单查看。 在每个TableRow中,我都放入一个TextView。现在有两个问题:
长于屏幕的文本不会自动换行为多行。 是TableRow设计的吗? 我已经设置了
LayoutParams.**WRAP_CONTENT**,
LayoutParams.WRAP_CONTENT));
Table不会像ListView一样滚动。 我的行大于屏幕大小。 我希望该表可以像ListView一样向下滚动以进行查看。 那可能吗?
这是我的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | TableLayout tl = (TableLayout) findViewById(R.id.article_content_table); TextView tr_title = new TextView(this); TextView tr_author_time = new TextView(this); TextView tr_content = new TextView(this); TableRow tr = new TableRow(this); for(int i = 0; i < BlogPost.size(); i++){ try{ // add the author, time tr = new TableRow(this); /////////////////add author+time row BlogPost article = mBlogPost.get(i); tr_author_time = new TextView(this); tr_author_time.setText(article.author+"("+ article.post_time+")"); tr_author_time.setTextColor(getResources().getColor(R.color.black)); tr_author_time.setGravity(0x03); tr_author_time.setLayoutParams(new LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); tr.addView(tr_author_time); tl.addView(tr,new TableLayout.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); ////////////////////// then add content row tr = new TableRow(this); tr_content = new TextView(this); tr_content.setText(article.content); tr_content.setSingleLine(false); tr_content.setGravity(0x03); tr_content.setLayoutParams(new LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); tr.addView(tr_content); tr.setBackgroundResource(R.color.white); tl.addView(tr,new TableLayout.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); } |
包装项目更合适的方法是将android:shrinkColumns =" *"或android:shrinkColumns =" 1"添加到TableLayout中,这可能已经解决了包装问题。
详情
这并不是一个完整的答案,但实际上您似乎在努力地做。
与其手动构建TableRows,不如使用xml进行设置:
tablerow.xml:
1 2 3 4 5 | <TableRow xmlns:android="http://schemas.android.com/apk/res/android"> <TextView android:id="@+id/content" android:singleLine="false" android:textAppearance="@style/someappearance" /> </TableRow> |
在循环之前,请获取对LayoutInflater的引用:
1 | LayoutInflater inflater = getLayoutInflater(); |
然后,在循环中,使用LayoutInflater创建一个tablerow实例:
1 2 3 4 5 | TableRow row = (TableRow)inflater.inflate(R.layout.tablerow, tl, false); TextView content = (TextView)row.findViewById(R.id.content); content.setText("this is the content"); tl.addView(row); |
这将允许您在xml中设置布局,外观,布局参数,从而使其更易于阅读和调试。
对于滚动问题,您需要将TableLayout添加到ScrollView。在您的xml中是这样的:
1 2 3 | <ScrollView> <TableLayout android:id="@+id/arcitle_content_table" /> </ScrollView> |
要在表格行中换行:
默认情况下,TableLayout行适合其内容的宽度,而不管其越过屏幕边界。若要使比屏幕宽的文本单元格可以换行,请使用TableLayout上的
1 2 3 4 | <TableLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:shrinkColumns="*" /> |
-
android:shrinkColumns="*" 缩小所有列 -
android:shrinkColumns="0" 缩小第一列 -
android:shrinkColumns="1,2" 缩小第二和第三列
"缩小"和"拉伸"都考虑表的所有行以计算空间。
向下滚动TableLayout:
如果