How to set setOnClickListener listener in Chip component in android

In this android programming source code example, we are going to set setOnClickListener listener in Chip component in android.

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 set setOnClickListener listener in Chip component in android.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:padding="15dp"
    android:background="#CACACA">

    <com.google.android.material.chip.Chip
        android:id="@+id/user"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:text="User"
        android:layout_centerInParent="true"
        app:chipIcon="@drawable/ic_user"
        app:iconStartPadding="5dp"
        style="@style/Widget.MaterialComponents.Chip.Action"/>

</RelativeLayout>

MainActivity.java

import androidx.appcompat.app.AppCompatActivity;

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

import com.google.android.material.chip.Chip;

public class AndroidChipActivity5 extends AppCompatActivity {
    private Chip chip;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_android_chip5);
        chip = (Chip)findViewById(R.id.user);
        chip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(AndroidChipActivity5.this, "User Click",Toast.LENGTH_LONG).show();
            }
        });
    }
}

values/styles.xml

<style name="ChipTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

app/build.gradle

implementation 'com.google.android.material:material:1.0.0'

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