Reputation:
I am trying to call Methods via DataBinding from the ViewModel. I have tried changing the code inside the layout file for onClick, but nothing works. It shows this error:
Listener class android.view.View.OnClickListener with method onClick did not match signature of any method model::click
<?xml version="1.0" encoding="utf-8"?>
<layout>
<data>
<variable
name="model"
type="com.example.myapplication.MainActivityViewModel" />
</data>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:text="Hey I am a Text View"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Press Me"
android:onClick="@{model::click}"/>
</RelativeLayout>
</layout>
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProviders;
import android.os.Bundle;
import com.example.myapplication.databinding.ActivityMainBinding;
public class MainActivity extends AppCompatActivity {
ActivityMainBinding binding;
MainActivityViewModel viewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this,R.layout.activity_main);
viewModel = ViewModelProviders.of(this).get(MainActivityViewModel.class);
binding.setModel(viewModel);
}
}
package com.example.myapplication;
import android.util.Log;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import static android.content.ContentValues.TAG;
public class MainActivityViewModel extends ViewModel {
public void click(){
Log.d(TAG, "click: This Button got Clicked");
}
}
I want a Log Message, when the Button is clicked
Upvotes: 0
Views: 2058
Reputation: 1214
Define your click handler like so:
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Press Me"
android:onClick="@{() -> model.click()}"/>
Upvotes: 1
Reputation: 3562
You need a View
object parameter in your onclick fundtion:
public void click(View view){
Log.d(TAG, "click: This Button got Clicked");
}
From documentation, your function must meet following requirements:
Be public
Return void
Define a View as its only parameter (this will be the View that was clicked)
This parameter is important because you can set this function to listen to multiple views instead of creating a separate function for every view. Then you can compare this object with your views to check which one was clicked.
Upvotes: 3