0

我有一个简单的复合视图ConstraintLayout作为根。clickable,等属性focusable已启用。它完美地显示在我的布局中。我想在它被点击时处理。方法很简单,但它不起作用:

myCompoundView.setOnClickListener {
     /// Handle click here 
}

但是根本不调用该回调。我真的不明白为什么它拒绝被调用。另一种方法如下:

  1. 为您的复合视图实现 OnClickListener
  2. 调用您setOnClickListenerinit复合视图
  3. 创建您自己的回调并在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()

    }


    }
4

2 回答 2

0

我找到了一些解决方案。让id我的复合视图的根布局称为root. 如果我们设置setOnClickListener如下:

myCompoundView.root.setOnClickListener {
     /// Handle here 
}

它以某种方式神奇地起作用。

于 2019-12-13T05:53:50.207 回答
0

确保您正在单击父视图。

如果子视图clickable并且focusabletrue

所以尝试设置false子视图,然后clickable尝试focusable

希望能帮助到你..

于 2019-12-13T05:56:49.673 回答