15

Android プロジェクトで Anko を使用していますが、参照先のビューが参照先と同じレベルにない場合に、DSL で作成した子ビューを参照する方法がわかりません。

次のコードが機能します。

alert {
    customView {
        val input = textInputLayout {
            editText {
                hint = "Name"
                textColor =resources.getColor(R.color.highlight)
            }
        }


        positiveButton("OK") { "${input.editText.text}" }
    }
}.show()

ただし、次のコードは機能しません。

alert {
    customView {
        val vertical = verticalLayout {
            textView {
                text = "Edit device name"
                textColor = resources.getColor(R.color.highlight)
                textSize = 24F
            }
            val input = textInputLayout {
                editText {
                    hint = "Name"
                    textColor = resources.getColor(R.color.highlight)
                }
            }
        }

        positiveButton("OK") { "${vertical.input.editText.text}" }  // Cannot resolve "input"
    }
}.show()
4

5 に答える 5

2

findViewById() の使用を提案します

alert {
        customView {
            val vertical = verticalLayout {
                textView {
                    text = "Edit device name"
                    textSize = 24F
                }
                val input = textInputLayout {
                    editText {
                        id = R.id.my_id_resource // put your id here
                        hint = "Name"
                    }
                }
            }
            positiveButton("OK") { "${(vertical.findViewById(R.id.my_id_resource) as? EditText)?.text}" }  
        }
    }.show()
于 2015-12-14T01:12:04.113 に答える
1

verticalコンテキストを手動で渡して、いつでもビューを昇格できます。

customView {
    val vertical = verticalLayout {
        textView {
            text = "Edit device name"
            textColor = resources.getColor(R.color.highlight)
            textSize = 24F
        }
    }

    val input = /*here:*/ vertical.textInputLayout {
        editText {
            hint = "Name"
            textColor = resources.getColor(R.color.highlight)
        }
    }

    positiveButton("OK") { "${input.editText.text}" }
}
于 2015-12-14T08:58:31.947 に答える
0

おそらく最善の方法は、後で参照する必要がある要素とfind<T : View>(Int) : T関数に Android ID を使用することです。これにより、ビューがまだ存在し、アプリケーション/アクティビティ スコープにアクセスできる限り、どこからでもそれらを参照できます。

詳細については、Anko のドキュメントを参照してください。

事例: 既存のビューにボタンを動的に追加する

verticalLayout {
  id = R.id.button_container
}
//note that the code below here may be executed anywhere after the above in your onCreate function
//verticalLayout is a Anko subclass of LinearLayout, so using the android class is valid.
val buttonContainer = find<LinearLayout>(R.id.button_container)

val containerContext = AnkoContext.Companion.create(ctx, buttonContainer)
val button = ctx.button {
  text = "click me"
  onClick = { toast("created with IDs!") }
}
buttonContainer.addView(button.createView(containerContext, buttonContainer))
于 2016-08-01T18:58:10.073 に答える