【问题标题】:Why it is not possible to use setOnClickListener directly for compound view?为什么不能直接将 setOnClickListener 用于复合视图?
【发布时间】:2020-04-06 13:18:08
【问题描述】:

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

myCompoundView.setOnClickListener {
     /// Handle click here 
}

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

  1. 为您的复合视图实现 OnClickListener
  2. 在您的复合视图的init 上致电setOnClickListener
  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()

    }


    }

【问题讨论】:

  • 禁用 clickablefocusable 子视图,它可以工作
  • 请出示您的代码。
  • 检查listner是否设置..可能是你在没有被调用的块中设置listner

标签: android onclick android-compound-view


【解决方案1】:

确保您点击的是父视图。

如果子视图clickablefocusabletrue,它可能不起作用

所以尝试在子视图上将false 设置为clickablefocusable,然后尝试

希望对你有帮助..

【讨论】:

  • 看,它有以 ConstraintsLayout 作为根(父)布局的复合视图,它启用了可聚焦、可点击。它的子视图没有这样的属性。我不知道如何尝试你的建议。禁用父视图的可点击、可聚焦?
  • 可能默认被认为是true,如果不行请出示你的代码
  • 没有尝试您的方法,但在问题中显示了代码
  • 我在下面回答了我自己的问题,为什么它有效?你能解释一下吗?
【解决方案2】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-01
    • 1970-01-01
    • 2021-03-24
    • 2016-11-13
    • 2014-11-25
    相关资源
    最近更新 更多