【发布时间】:2020-04-06 13:18:08
【问题描述】:
我有一个以ConstraintLayout 为根的简单复合视图。 clickable、focusable 等属性已启用。它完美地显示在我的布局中。我想在它被点击时处理。方法很简单,但行不通:
myCompoundView.setOnClickListener {
/// Handle click here
}
但是根本没有调用该回调。我真的不明白为什么它拒绝被调用。另一种方法如下:
- 为您的复合视图实现 OnClickListener
- 在您的复合视图的
init上致电setOnClickListener - 创建您自己的回调并在
onClick被调用时使用它
但是这种方法需要更多代码,而且它只是实现了已经完成的内容。回调可能会在某个时候变为空。所以,我的问题是为什么简单的setOnClickListener 不起作用?如果它不起作用,当我的复合视图被点击时如何得到通知?
如果需要,有代码:
/// 下面是我的复合视图
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://sch`enter code here`emas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:clickable="true"
android:focusable="true"
android:id="@+id/root"
android:background="?attr/selectableItemBackground"
>
/// some views here
</androidx.constraintlayout.widget.ConstraintLayout>
这是我的使用方法:
<sample.sample.com.ChooserView
android:id="@+id/familyStateChooserView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:chooseLabel="@string/family_kind"
android:layout_marginTop="8dp"
/>
这是它的类:
class ChooserView(
context: Context,
attrs: AttributeSet
) : ConstraintLayout(context, attrs) {
init {
LayoutInflater.from(context)
.inflate(R.layout.chooser_view, this, true)
val typedArray = context.obtainStyledAttributes(attrs, R.styleable.ChooserView, 0, 0)
label.text = typedArray.getString(R.styleable.ChooserView_chooseLabel)
typedArray.recycle()
}
}
【问题讨论】:
-
禁用
clickable和focusable子视图,它可以工作 -
请出示您的代码。
-
检查listner是否设置..可能是你在没有被调用的块中设置listner
标签: android onclick android-compound-view