У меня есть 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") }
}