Как получить номер столбца при нажатии из динамически созданной таблицы в Android? - PullRequest
1 голос
/ 04 августа 2020

У меня есть таблица, которая создается программно в приложении. Я могу получить позицию выбранной строки и назначить ее переменной, но я не уверен, как вообще выполнить эквивалент для столбцов. Все, что мне действительно нужно знать, это как получить номер столбца при нажатии, как я делаю со строками здесь:

fun createTable(rows: Int, cols: Int) {
        /* Here, 'i' represents the number of rows, which is determined by
        * the length of the location list active in the application. */
        for (i in 0 until locationList.size) {
            /* Instantiate the row that will be used to generate each table. */
            val row = TableRow(this)

            /* Set the basic layout parameters for the textView, which is being used to contain the table. */
            row.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)

            row.setOnClickListener {
                selectedRow = i.toString().toInt()

                if (locationList[selectedRow].entranceNoteArray.size == 0) {
                    showAlert("There are no transitions associated with this location. You may only add a note to an existent transition.")
                } else {
                    isEnterOrExit()
                }
            }

            row.gravity = Gravity.CENTER

            for (j in 0 until columns) {
                var rowIterator = 0
                val textView = TextView(this)

                textView.apply {
                    // Cosmetic/UI Related Code
                    textView.setPadding(10, 5, 10, 5)
                    layoutParams = TableRow.LayoutParams(350, TableRow.LayoutParams.WRAP_CONTENT)
                    textView.setTextColor(Color.DKGRAY)
                    textView.gravity = Gravity.CENTER
                    textView.textSize = 12F

                    /* The purpose of this decision structure is to fill the
                    * table's cells properly based upon which column cell 'j'
                    * represents. When j = 0 and i = 0, the first column of
                    * the first row has been selected - therefore, the first
                    * value (message) of the first location in the reversed
                    * locationList should be placed there. */
                    if (j == 0) {
                        text = locationList[i].message
                        textView.setTypeface(null, Typeface.BOLD)
                    } else if (j == 1) {
                        text = locationList[i].entered
                        textView.setTypeface(null, Typeface.NORMAL)
                    } else if (j == 2) {
                        text = locationList[i].exited
                    }
                }
                row.addView(textView)
                rowIterator++
            }
            tableLayout.addView(row)
        }
        logLayout.addView(tableLayout)
    }

Есть ли простой способ сделать это, или мне нужно получить координаты при нажатии из самого обзора, чтобы достичь этого окольным путем?

1 Ответ

1 голос
/ 05 августа 2020

Если вы хотите узнать, какой именно TextView был нажат в таблице, вы можете сделать это следующим образом:

  1. Foreach TextView Вы должны добавить tag
textView.tag = "$i $j"

i - строка, а j - столбец.

Теперь вы можете добавлять по одному слушателю на каждые TextView
textView.setOnClickListener {
    val tag = it.tag.toString()
    val row = tag.substring(0, tag.indexOf(' ')).toInt()
    val column = tag.substring(tag.indexOf(' ') + 1).toInt()
            
    //now You know which position was clicked
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...