Android Kotlin中为何无法访问动态添加到TableLayout的TableRow?
问题原因
你动态添加到TableLayout的不是TableRow,而是ConstraintLayout。因为你通过LayoutInflater加载的R.layout.table_item的根布局是ConstraintLayout,当你把这个加载后的View直接添加到TableLayout时,TableLayout的子项就是这个ConstraintLayout容器,而非TableRow。所以调用getChildAt(1)拿到的是ConstraintLayout,强转成TableRow必然抛出ClassCastException。
解决办法
方案1:修改table_item.xml的根布局为TableRow
直接把table_item.xml的根标签从<androidx.constraintlayout.widget.ConstraintLayout>改成<TableRow>,确保加载的布局本身就是TableRow。这样添加到TableLayout后,getChildAt拿到的就是TableRow,强转不会出错。
示例修改后的table_item.xml结构:
<TableRow xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content"> <!-- 这里放TableRow里的子View,比如TextView等 --> <TextView android:id="@+id/tv_col1" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:text="内容"/> </TableRow>
方案2:保留原根布局,获取内部的TableRow
如果因为布局需求必须保留ConstraintLayout作为table_item.xml的根,那可以通过两种方式处理:
方式A:添加时只传入TableRow
加载布局后,先找到内部的TableRow再添加到TableLayout:
val itemView = LayoutInflater.from(this).inflate(R.layout.table_item, tableLayout, false) val tableRow = itemView.findViewById<TableRow>(R.id.your_table_row_id) tableLayout.addView(tableRow)
方式B:获取时从ConstraintLayout中取出TableRow
如果已经把ConstraintLayout添加到了TableLayout,获取子项时先拿到ConstraintLayout,再从中取出内部的TableRow:
val childView = tableLayout.getChildAt(1) if (childView is ConstraintLayout) { val tableRow = childView.findViewById<TableRow>(R.id.your_table_row_id) // 这里对tableRow进行后续操作 }
内容的提问来源于stack exchange,提问作者ThN
相关产品推荐
相关产品推荐

