【发布时间】:2019-02-05 10:00:56
【问题描述】:
我正在尝试使用扩展 RelativeLayout 并命名为 CardView 的自定义视图。 A 添加了一些 attr 并为它们创建了 XML 文件,一切正常,除了onClick。所以,起初我为我的视图创建了一个特殊的类:
class CardView(context: Context, attrs: AttributeSet) : RelativeLayout(context, attrs) {
init {
inflate(context, R.layout.card_view, this)
val imageView: ImageView = findViewById(R.id.image)
val textView: TextView = findViewById(R.id.caption)
val line: ImageView = findViewById(R.id.line)
val attributes = context.obtainStyledAttributes(attrs, R.styleable.CardView)
imageView.setImageResource(attributes.getResourceId(R.styleable.CardView_image, 0))
textView.text = attributes.getString(R.styleable.CardView_text)
line.setBackgroundColor(attributes.getColor(R.styleable.CardView_lineColor, 0))
attributes.recycle()
} }
我的视图也有一个 xml 文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="@dimen/cardSize"
android:layout_height="@dimen/cardSize"
android:background="@drawable/card_color_selector"
android:clickable="true">
<ImageView
android:id="@+id/image"
android:layout_width="60sp"
android:layout_height="60sp"
android:layout_centerHorizontal="true"
android:layout_margin="3sp"
tools:src="@color/colorPrimary" />
<TextView
android:id="@+id/caption"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/text_normal"
android:textSize="15dp"
android:layout_alignParentBottom="true"
android:layout_margin="10sp"
android:gravity="center"
android:textColor="@color/darkGray"
tools:text="Caption" />
<ImageView
android:id="@+id/line"
android:layout_width="match_parent"
android:visibility="visible"
android:layout_height="5dp"
android:layout_alignParentBottom="true"
android:background="@color/colorPrimary" />
</RelativeLayout>
最后我在活动布局中添加了我的customView,并在视图模型中添加了指向onClick 方法的链接,如下所示:
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="viewModel"
type="com.presentation.screen.HomeViewModel" />
</data>
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.project.presentation.utils.CardView
android:id="@+id/card"
android:layout_width="@dimen/cardSize"
android:layout_height="@dimen/cardSize"
android:clickable="true"
android:onClick="@{() -> viewModel.onClick()}"
app:image="@drawable/icon"
app:lineColor="@color/colorPrimary"
app:text="@string/text" />
</android.support.constraint.ConstraintLayout>
</layout>
所以一切都很好,颜色改变了,就像我在card_color_selector.xml 中写的那样,但是我的ViewModel 中的方法onClick 从未调用过。哦,顺便说一句,我的视图模型在这里,现在我只想记录所有点击:
class HomeViewModel : BaseViewModel<Router>() {
fun onClick() {
Log.e("myLog", "HomeViewModel onClick")
}
}
我什么都试过了!请帮我弄清楚我做错了什么。
【问题讨论】:
标签: android data-binding onclick android-custom-view android-databinding