【发布时间】:2019-09-11 15:33:26
【问题描述】:
我有 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") }
}
【问题讨论】:
-
你在哪里实现点击监听?
-
你能发
logMessage的代码 -
你应该也添加了
item_custom_btn,但它可能只是setClickable(true); setFocusable(true);在ButtonWithImage构造函数中丢失了
标签: android android-fragments kotlin listener android-custom-view