Android Kotlin:为何无法访问TableLayout中的隐藏表格列?
无法访问TableLayout隐藏列的原因及解决方法
问题原因
你的TableRow被包裹在ConstraintLayout中作为根布局,但测试代码错误地将TableLayout的直接子View(即这个ConstraintLayout)强转为TableRow。此时调用getChildAt(0)实际获取的是ConstraintLayout的子View(TableRow),而非TableRow内部的隐藏列TextView,导致你拿到的是错误的控件值。
另外,依赖getChildAt(index)获取控件的方式本身不够可靠,一旦布局结构调整,索引就会失效。
解决方法
方法1:修正控件获取逻辑
先获取包裹TableRow的ConstraintLayout,再从中取出目标TableRow和隐藏列:
val constraintLayout = stableLayout.getChildAt(0) as ConstraintLayout val tableRow = constraintLayout.getChildAt(0) as TableRow val cIdout = tableRow.getChildAt(0) as TextView Toast.makeText(this@MainActivity, cIdout.text, Toast.LENGTH_SHORT).show()
方法2:优化布局结构(推荐)
去掉外层多余的ConstraintLayout,直接将TableRow作为行布局的根节点,简化获取逻辑:
修改行的XML:
<?xml version="1.0" encoding="utf-8"?> <TableRow xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:id="@+id/idautoint" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="0.25" android:gravity="start" android:visibility="invisible" /> <TextView android:id="@+id/name" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="0.25" android:gravity="start" /> <TextView android:id="@+id/title" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="0.25" android:gravity="start" /> </TableRow>
此时你的原测试代码即可正常工作,或者更推荐通过ID获取控件:
val tableRow = stableLayout.getChildAt(0) as TableRow val cIdout = tableRow.findViewById<TextView>(R.id.idautoint) Toast.makeText(this@MainActivity, cIdout.text, Toast.LENGTH_SHORT).show()
方法3:通过ID直接获取(最可靠)
无论布局结构如何,直接通过控件ID获取是最稳定的方式,避免索引变化导致的错误:
val rowContainer = stableLayout.getChildAt(0) val cIdout = rowContainer.findViewById<TextView>(R.id.idautoint) Toast.makeText(this@MainActivity, cIdout.text, Toast.LENGTH_SHORT).show()
内容的提问来源于stack exchange,提问作者ThN
相关产品推荐
相关产品推荐

