Метод OnClick для пользовательского представления никогда не вызывался (Android) - PullRequest
0 голосов
/ 05 февраля 2019

Я пытаюсь использовать пользовательское представление, которое расширяет RelativeLayout с именем CardView.Добавил немного 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, но метод onClick по моему ViewModel никогда не звонил.О, кстати, моя модель обзора здесь, теперь я просто хочу зарегистрировать все клики:

class HomeViewModel : BaseViewModel<Router>() {

    fun onClick() {
        Log.e("myLog", "HomeViewModel onClick")
    }
}

Я перепробовал все!Пожалуйста, помогите мне понять, что я делаю неправильно.

Ответы [ 4 ]

0 голосов
/ 24 августа 2019

У меня была такая же проблема.

Проверьте кликабельный атрибут вашего настраиваемого представления!

Если ваш дочерний вид в настраиваемом представлении предотвращает событие касания, ваш родительский

android:onClickбудет игнорироваться.

0 голосов
/ 05 февраля 2019

Измените свой onClick метод, подобный этому. Попробуйте вот так

fun onClick(view: View) {
        Log.d("myLog", "HomeViewModel onClick")
    }
0 голосов
/ 05 февраля 2019

У меня недостаточно репутации, чтобы комментировать, поэтому вы можете попробовать

    android:onClick="@{(v) -> viewModel.onClick(v)}"

и функцию

     fun onClick(view:View) {
    Log.e("myLog", "HomeViewModel onClick")
     }
0 голосов
/ 05 февраля 2019

В вашем

fun onClick() {
    Log.e("myLog", "HomeViewModel onClick")
} 

pass View В разделе XML для

onClick = "method" вы должны установить параметр как View класс в вашем методе.

Вы можете видеть это

...