所以,我在一个 xml 文件中有一个 TableLayout
和 4 个 TableRow
。我还有一个定义 TextView
的 xml 文件,它将插入行中(每行 3 个 TextView
)。
我希望那些 TextView
具有相同的宽度,并且当所有内容都在同一个 xml 文件中时效果很好(开始时我的 TextView
是“硬编码” ) 但现在我以编程方式添加它们,它们的宽度不同。
这是第一个 XML 文件
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/homeTable"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/lmbg"
android:clickable="true"
android:padding="20dp" >
<TableRow
android:id="@+id/tableRow1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="center"
android:minHeight="200dp" >
</TableRow>
<TableRow
android:id="@+id/tableRow2"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="center"
android:minHeight="200dp" >
</TableRow>
<TableRow
android:id="@+id/tableRow3"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="center"
android:minHeight="200dp" >
</TableRow>
<TableRow
android:id="@+id/tableRow4"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="center"
android:minHeight="200dp" >
</TableRow>
</TableLayout>
这是我的 TextView
项目
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:layout_weight="1"
android:clickable="true"
android:gravity="center"
android:onClick="goToList"
android:textSize="14sp" />
最后这就是我以编程方式添加它们的方式
for(int i = 0; i < mTopCategories.size(); i++){
Category c = mTopCategories.get(i);
TableRow row = ((TableRow)findViewById(rowID[idIdx])) ;
cat = (TextView) getLayoutInflater().inflate(R.layout.cat_grid_item, null);
int iconID = getResources().getIdentifier(c.getSlug().replace('-', '_'), "drawable", getPackageName());
cat.setCompoundDrawablesWithIntrinsicBounds(0, iconID, 0, 0);
int textID = getResources().getIdentifier(c.getSlug().replace('-', '_'), "string", getPackageName());
cat.setText(textID);
cat.setTag(c.getId().toString());
row.addView(cat);
}
最佳答案
尝试像这样在 TextView 上显式设置布局参数:
TableRow.LayoutParams lParams = new TableRow.LayoutParams(0, -2 /* WRAP_CONTENT */, 0.33f /* 33% of width */);
cat.setLayoutParams(lParams);
关于android - TableRow 中以编程方式添加的元素的权重不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24325420/