我有一个简单的复合视图ConstraintLayout
作为根。clickable
,等属性focusable
已启用。它完美地显示在我的布局中。我想在它被点击时处理。方法很简单,但它不起作用:
myCompoundView.setOnClickListener {
/// Handle click here
}
但是根本不调用该回调。我真的不明白为什么它拒绝被调用。另一种方法如下:
- 为您的复合视图实现 OnClickListener
- 调用您
setOnClickListener
的init
复合视图 - 创建您自己的回调并在
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()
}
}