Android - 带有按钮和文本的点击视图
Android - Onclick View with button and text
我有一个使用 anko DSL 构建的自定义按钮:
fun customButton(label: String): View {
return UI {
verticalLayout {
button {
id = BTN_SERVICE_ITEM_ID
}.lparams(dip(64), dip(64))
textView {
text = label
}.lparams(wrapContent, wrapContent)
}
}.view
}
然后我在该按钮上添加 setOnClickListener
val customButton = customButton("service 1")
layout.addView(customButton)
customButton.setOnClickListener {
toast("clicked")
}
当我点击按钮时,没有显示吐司。但是当点击自定义按钮的区域时,会显示toast。
我知道我可以使用 findViewById
获取按钮然后向其添加 setOnClickListener
。但是,有什么方法可以让我将 onClickListener 附加到视图吗?
编辑:
我已经尝试在按钮上添加 isEnabled=false
、isClickable=false
、isFocusable=false
、isActivated=false
和 setOnClickListener(null)。仍然没有运气。
最简单的解决方案就是将 View.OnClickListener
的实例传递给您的方法 customButton
。
我不熟悉 anko 语法,但它看起来应该类似于:
fun customButton(label: String, clickListener: View.OnClickListener): View {
return UI {
verticalLayout {
button {
id = BTN_SERVICE_ITEM_ID
onClickListener = clickListener
}.lparams(dip(64), dip(64))
textView {
text = label
}.lparams(wrapContent, wrapContent)
}
}.view
}
毕竟,如果您要创建一个专用方法来创建按钮,为什么不使用它:)
我有一个使用 anko DSL 构建的自定义按钮:
fun customButton(label: String): View {
return UI {
verticalLayout {
button {
id = BTN_SERVICE_ITEM_ID
}.lparams(dip(64), dip(64))
textView {
text = label
}.lparams(wrapContent, wrapContent)
}
}.view
}
然后我在该按钮上添加 setOnClickListener
val customButton = customButton("service 1")
layout.addView(customButton)
customButton.setOnClickListener {
toast("clicked")
}
当我点击按钮时,没有显示吐司。但是当点击自定义按钮的区域时,会显示toast。
我知道我可以使用 findViewById
获取按钮然后向其添加 setOnClickListener
。但是,有什么方法可以让我将 onClickListener 附加到视图吗?
编辑:
我已经尝试在按钮上添加 isEnabled=false
、isClickable=false
、isFocusable=false
、isActivated=false
和 setOnClickListener(null)。仍然没有运气。
最简单的解决方案就是将 View.OnClickListener
的实例传递给您的方法 customButton
。
我不熟悉 anko 语法,但它看起来应该类似于:
fun customButton(label: String, clickListener: View.OnClickListener): View {
return UI {
verticalLayout {
button {
id = BTN_SERVICE_ITEM_ID
onClickListener = clickListener
}.lparams(dip(64), dip(64))
textView {
text = label
}.lparams(wrapContent, wrapContent)
}
}.view
}
毕竟,如果您要创建一个专用方法来创建按钮,为什么不使用它:)