片段不响应自定义视图上的 onClick 事件

Fragment does not respond to onClick event on custom views

我有 MainFragment,在我的片段中添加了 CustomButton 自定义视图。并且,onViewCreated,我将 OnClickListener 设置到视图。但是,fragmenet 没有响应点击。

ButtonWithImage

class ButtonWithImage(context: Context, attrs: AttributeSet) : LinearLayout(context, attrs) {

    init {
        val view = View.inflate(context, R.layout.item_custom_btn, this)

        val attributes = context.obtainStyledAttributes(attrs, R.styleable.BadgeIcon)

        view.btn_image.setImageDrawable(attributes.getDrawable(R.styleable.BadgeIcon_image))
        view.btn_text.setText(attributes.getResourceId(R.styleable.BadgeIcon_text, 0))

        attributes.recycle()
    }

}

fragment_main.xml

...
    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:orientation="horizontal">

        <corn.transaction.custom_view.ButtonWithImage
                android:id="@+id/my_cards"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="match_parent"
                app:image="@drawable/ic_my_cards"
                app:text="@string/btn_text_my_cards"/>

        <corn.transaction.custom_view.ButtonWithImage
                android:id="@+id/transactions"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="match_parent"
                app:image="@drawable/ic_transactions"
                app:text="@string/btn_text_transactions"/>

    </LinearLayout>
...

MainFragment.kt

class MainFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? = inflater.inflate(R.layout.fragment_main, container, false)


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        my_cards.setOnClickListener { logMessage("loooooog") }
    }

我认为你可以通过以下方式修复它:

  1. focusable=falseclickable=false 添加到您的 btn_imagebtn_text
  2. focusable=trueclickable=true 添加到此自定义布局的根视图中(同时为其提供 ID -> 让我们说 custom_button_container
  3. 致电my_cards.findViewById<LinearLayout>(R.id.custom_button_container).setOnClickListener { logMessage("loooooog") }

最佳解决方案是使 XML 中的所有视图都可点击且可聚焦为 false。

您可以使用以下代码:

my_cards.setOnClickListener { logMessage("loooooog") }

由于所有视图都不可点击和聚焦,因此它们会忽略点击,但不会忽略自定义视图本身。