我想实现类似的东西( RTL ):
换句话说,能够在3列中添加视图到布局。 我试过这样做:
my_fragment.xml:
...
<TableLayout
android:id="@+id/myTable"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numColumns="3"
android:stretchColumns="*"
android:layout_margin="10dp"
android:background="@color/background_color">
</TableLayout >
...
myFragment.java:
TableRow[] tableRows = new TableRow[ serverResponse.getData().size()/3 ];
for( int i=0, j=0; i<serverResponse.getData().size() ;i++ )
{
View customView = inflater.inflate(R.layout.data_item, tableRows[j], true);
((TextView) customView.findViewById(R.id.viewText)).setText(serverResponse.getData().get(i).getItemData());
if( i%3 == 0 ) {
j++;
}
myTable.addView( tableRows[i] , new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT) );
}
崩溃:Cannot add a null child view to a ViewGroup
编辑: 感谢Mike M的解决方案,它现在有效。但是,总是会删除一列:
data_item.xml很简单:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right">
<TextView
android:id="@+id/viewText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:ellipsize="end"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="8dp"
android:background="@drawable/circle"/>
</LinearLayout>
答案 0 :(得分:1)
您收到该错误是因为您没有初始化TableRow
数组的各个元素。初始化数组本身不会初始化元素。也就是说,您需要为每个数组索引实例化一个新的TableRow
。
此外,您需要使用TableRow
方法将单元格添加到每个addView()
,而不是将它们充气到其中,或者每个新单元格占据整行。
final int size = serverResponse.getData().size();
final int numCols = 3;
final int numRows = size / numCols + (size % numCols == 0 ? 0 : 1);
final TableRow[] tableRows = new TableRow[numRows];
final TableLayout.LayoutParams tableParams =
new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT);
final TableRow.LayoutParams rowParams =
new TableRow.LayoutParams(0,
TableRow.LayoutParams.WRAP_CONTENT,
1);
for (int i = 0; i < numRows; i++) {
tableRows[i] = new TableRow(getContext());
for (int j = 0; j < numCols; j++) {
final int index = i * numCols + j;
final View customView = inflater.inflate(R.layout.data_item,
tableRows[i], false);
if (index < size) {
((TextView) customView.findViewById(R.id.noteText))
.setText(serverResponse.getData().get(index).getItemData());
}
else {
((ImageView) customView.findViewById(R.id.circle))
.setVisibility(View.INVISIBLE);
}
tableRows[i].addView(customView, rowParams);
}
myTable.addView(tableRows[i], tableParams);
}
在data_item
布局中,在circle
上设置ImageView
的ID。