【发布时间】:2021-12-23 21:16:24
【问题描述】:
我创建了一个用按钮填充的 TableLayout。
我希望按钮在单击后改变颜色。但是会有 100 个按钮,所以我不认为为每个按钮创建一个 id 和一个 onClickListener() 是正确的方法。
有没有一种方法可以告诉我点击了哪个按钮,而无需将 id 委派给每个按钮?
<TableRow
android:layout_height="0dp"
android:layout_weight="1"
android:id="@+id/row1"
>
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Button 1"
/>
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Button 2"
/>
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Button 3"
/>
</TableRow>
<TableRow
android:layout_height="0dp"
android:layout_weight="1"
>
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Button 4"
/>
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Button 5"
/>
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Button 6"
/>
</TableRow>
<TableRow
android:layout_height="0dp"
android:layout_weight="1"
>
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Button 7"
/>
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Button 8"
/>
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Button 9"
/>
</TableRow>
我见过一些类似的问题,但是当我实施它们时,似乎什么也没发生。这是在我的主要活动中,我尝试记录按钮单击但没有记录任何内容。
val table : TableLayout = findViewById(R.id.table1)
val row : TableRow = findViewById(R.id.row1)
row.setOnClickListener(object : View.OnClickListener{
override fun onClick(p0: View?) {
val tr = p0?.getParent() as TableRow
val rowIndex: Int = table.indexOfChild(p0)
Log.i("TAG!!!!!!!!!!!!!!!", "onClick: " + tr)
}
})
【问题讨论】:
标签: android kotlin android-layout