我们可以获取在android / kotlin中动态创建的gridlayout的单元格文本值吗?

时间:2019-03-10 20:05:18

标签: android kotlin

这是一个动态创建的6 * 6网格布局。我想获取每个单元格中文本的值,以便当用户单击板上具有特定文本(例如:动物)的单元格时,应禁用该单元格,并且不能对该单元格进行任何单击。 / p>

如何在gridlayout中获取动态创建的单元格的文本值?

创建木板的代码(acticity.kt):

 fun createBoard(context: Context, board: GridLayout, size: Int, listofThings: List<String>) {
        destroyBoard()
        board.columnCount = size
        board.rowCount = size
        var iterator = 0
        for(col in 1..size) {
            for (row in 1..size) {
                cell = RelativeLayout(context)
                val cellSpecifications = { GridLayout.spec(GridLayout.UNDEFINED, GridLayout.FILL, 1f) }
                val params = GridLayout.LayoutParams(cellSpecifications(), cellSpecifications())
                params.width = 0
                cell.layoutParams = params
                cell.setBackgroundResource(R.drawable.bordered_rectangle)
                cell.gravity = Gravity.CENTER
                cell.setPadding(5, 0, 5, 0)

                text = TextView(context)
                text.text = people[iterator++]
                words.add(text.text as String)
                
                text.maxLines = 5
                text.setSingleLine(false)
                text.gravity = Gravity.CENTER
                text.setTextColor(0xFF000000.toInt())

                cell.addView(text)
                board.addView(cell)
                cells.add(GameCell(cell, text, false, row, col) {  })
            }
        }
    }

activity.xml中的代码:

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <android.support.v7.widget.GridLayout
            android:id="@+id/grid"
            android:layout_gravity="center"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="16dp"
            android:layout_marginEnd="16dp"
            android:layout_marginStart="16dp"
            android:layout_marginTop="16dp"
            android:layout_weight="1"
          >

        </android.support.v7.widget.GridLayout>
        
</LinearLayout>

1 个答案:

答案 0 :(得分:1)

调用createBoard方法后,可以在GridLayout的每个单元格上设置一个侦听器。

val board = findViewById<android.support.v7.widget.GridLayout>(R.id.grid)

createBoard(this, board, 3, listOf<String>())

val childCount = board.childCount
for (i in 0 until childCount) {
    val cell = board.getChildAt(i) as RelativeLayout
    cell.setOnClickListener { view ->
        val textView = (view as RelativeLayout).getChildAt(0) as TextView
        val textValue = textView.text
        // Process textValue here
        Toast.makeText(this, textValue, Toast.LENGTH_SHORT).show()
    }
}