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

问题描述 投票:0回答:1

我有MainFragment,在我的片段中我添加了CustomButton自定义视图。而且,onViewCreated,我将setOnClickListener添加到视图中。但是,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") }
    }

android android-fragments kotlin listener android-custom-view
1个回答
0
投票

我想你可以解决它:

  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") }
© www.soinside.com 2019 - 2024. All rights reserved.