How to add click event handler in Android Databinding

In this android programming source code example, we are going to add click event handler in Android Databinding.

You can copy and adopt this source code example to your android project without reinventing the wheel.

Below is a step by step source code to add click event handler in Android Databinding.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<layout 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">
    <data>
        <variable
            name="handlers"
            type="com.bluapp.androidview2.firebaseMlKitAndDataBinding.FirebaseMlKitAndDataBindingActivity15.ClickHandler"/>
    </data>
    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="30dp">

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Click Me"
            android:background="@color/colorAccent"
            android:textColor="#ffffff"
            android:onClick="@{handlers::onButtonClicked}"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"/>
    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

MainActivity.java

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.bluapp.androidview2.databinding.ActivityFirebaseMlKitAndDataBinding15Binding;

public class FirebaseMlKitAndDataBindingActivity15 extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityFirebaseMlKitAndDataBinding15Binding binding = DataBindingUtil.setContentView(this, R.layout.activity_firebase_ml_kit_and_data_binding15);
        ClickHandler clickHandler = new ClickHandler(this);
        binding.setHandlers(clickHandler);
    }

    public class ClickHandler{
        Context context;
        public ClickHandler(Context context){
            this.context = context;
        }

        public void onButtonClicked(View view){
            Toast.makeText(getApplicationContext(), "Button Clicked", Toast.LENGTH_LONG).show();
        }
    }
}

app/build.gradle

dataBinding {
        enabled = true
    }

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

Add a Comment