Фрагмент не отвечает на событие onClick в пользовательских представлениях - PullRequest
0 голосов
/ 22 апреля 2019

У меня есть MainFragment, и внутри моего фрагмента я добавил свой пользовательский вид CustomButton. И, на ViewCreated, я устанавливаю OnClickListener для представления. Но фрагмент не реагирует на щелчок.

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 Ответ

0 голосов
/ 22 апреля 2019

Я думаю, что вы можете это исправить:

  1. Добавление focusable=false и clickable=false к вашим btn_image и btn_text
  2. Добавление focusable=true и clickable=true к корневому представлению этого пользовательского макета (также укажите его идентификатор -> скажем, custom_button_container)
  3. Звоните my_cards.findViewById<LinearLayout>(R.id.custom_button_container).setOnClickListener { logMessage("loooooog") }
...