RecyclerView Button Android Studio Example Get Click Position

recyclerview button android

Welcome guys to RecyclerView Button Android Studio Example.

In this RecyclerView Button Android tutorial, you will learn to make recyclerview with button in it’s row item.

You will learn to “handle button click inside a row in recyclerview” in RecyclerView Button Android tutorial.

If you have not implement basic recyclerview with custom adapter yet, check recyclerview android example first.

Other useful tutorials,

Official guide for recyclerview : RecyclerView Official

Now checkout the output of RecyclerView Button Android example, then we will develop it.

Step 1: Create a new project in Android Studio.

When you create a new project in android studio, make default activity as an empty activity.

Step 2: Updating build.gradle(Module:app) file

Add below source code into dependencies{}

compile 'com.android.support:recyclerview-v7:23.4.0'
compile 'com.android.support:cardview-v7:23.3.+'

Step 3: Coding cardview.xml

Create a new file into drawable folder and name it cardview.xml

Add below source code into it.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_focused="true">
        <shape android:shape="rectangle">
            <padding
                android:left="4dp"
                android:top="4dp"
                android:right="4dp"
                android:bottom="4dp"
                />
            <gradient android:startColor="#1c88b7" android:endColor="#2972ba" android:angle="270" />

            <corners android:topLeftRadius="4dp" android:topRightRadius="4dp"/>
        </shape>
    </item>

    <item android:state_focused="false"
        >
        <shape android:shape="rectangle">
            <padding
                android:left="4dp"
                android:top="4dp"
                android:right="4dp"
                android:bottom="4dp"
                />

            <gradient android:startColor="#b71c83" android:endColor="#29ba41" android:angle="270" />

            <corners android:topLeftRadius="4dp" android:topRightRadius="4dp" />
        </shape>
    </item>

</selector>

Step 4: Making rv_item.xml

Create a new layout resource file named rv_item.xml

Copy following source code into it

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        card_view:cardCornerRadius="4dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#fadcdc"
            android:orientation="vertical">


            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="20dp"
                android:orientation="horizontal">

                <TextView
                    android:id="@+id/animal"
                    android:layout_width="130dp"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dp"
                    android:text="animal"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:textColor="#000"
                    android:textSize="20sp" />

                <TextView
                    android:id="@+id/number"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dp"
                    android:text="1"
                    android:textAppearance="?android:attr/textAppearanceLarge"
                    android:textColor="#000" />

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:orientation="horizontal">

                <Button
                    android:id="@+id/plus"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dp"
                    android:text="Plus"
                    android:textColor="#000" />

                <Button
                    android:id="@+id/minus"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Minus"
                    android:textColor="#000" />
            </LinearLayout>
        </LinearLayout>
    </android.support.v7.widget.CardView>
</LinearLayout>

Step 5: Making Model class

Create a new JAVA class named Model.java and paste below source code

package com.exampledemo.parsaniahardik.recyclerview_button;

/**
 * Created by hardik on 9/1/17.
 */
public class Model {

    private int number;
    private String fruit;

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public String getFruit() {
        return fruit;
    }

    public void setFruit(String fruit) {
        this.fruit = fruit;
    }
}

Step 6: Adding integer.xml

Create a new file named integer.xml  in values directory and copy below

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <integer name="btn_plus_view">1</integer>
    <integer name="btn_plus_pos">2</integer>
    <integer name="btn_minus_view">3</integer>
    <integer name="btn_minus_pos">4</integer>

</resources>

Step 7: Code for CustomAdapter.java

Let’s create Custom Adapter for RecyclerView.

Make a new JAVA class named CustomAdapter.java and paste below

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

/**
 * Created by Parsania Hardik on 29-Jun-17.
 */
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {

    private LayoutInflater inflater;
    private Context ctx;

    public CustomAdapter(Context ctx) {

        inflater = LayoutInflater.from(ctx);
        this.ctx = ctx;
    }

    @Override
    public CustomAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = inflater.inflate(R.layout.rv_item, parent, false);
        MyViewHolder holder = new MyViewHolder(view);

        return holder;
    }

    @Override
    public void onBindViewHolder(final CustomAdapter.MyViewHolder holder, int position) {

        holder.tvFruit.setText(MainActivity.modelArrayList.get(position).getFruit());
        holder.tvnumber.setText(String.valueOf(MainActivity.modelArrayList.get(position).getNumber()));

    }

    @Override
    public int getItemCount() {
        return MainActivity.modelArrayList.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        protected Button btn_plus, btn_minus;
        private TextView tvFruit, tvnumber;

        public MyViewHolder(View itemView) {
            super(itemView);

            tvFruit = (TextView) itemView.findViewById(R.id.animal);
            tvnumber = (TextView) itemView.findViewById(R.id.number);
            btn_plus = (Button) itemView.findViewById(R.id.plus);
            btn_minus = (Button) itemView.findViewById(R.id.minus);

            btn_plus.setTag(R.integer.btn_plus_view, itemView);
            btn_minus.setTag(R.integer.btn_minus_view, itemView);
            btn_plus.setOnClickListener(this);
            btn_minus.setOnClickListener(this);

        }

        // onClick Listener for view
        @Override
        public void onClick(View v) {

            if (v.getId() == btn_plus.getId()){

                View tempview = (View) btn_plus.getTag(R.integer.btn_plus_view);
                TextView tv = (TextView) tempview.findViewById(R.id.number);
                int number = Integer.parseInt(tv.getText().toString()) + 1;
                tv.setText(String.valueOf(number));
                MainActivity.modelArrayList.get(getAdapterPosition()).setNumber(number);

            } else if(v.getId() == btn_minus.getId()) {

                View tempview = (View) btn_minus.getTag(R.integer.btn_minus_view);
                TextView tv = (TextView) tempview.findViewById(R.id.number);
                int number = Integer.parseInt(tv.getText().toString()) - 1;
                tv.setText(String.valueOf(number));
                MainActivity.modelArrayList.get(getAdapterPosition()).setNumber(number);
            }
        }

    }
}

Describing CustomAdapter

We will set tags for Plus and Minus button with below source code

 btn_plus.setTag(R.integer.btn_plus_view, itemView);
 btn_minus.setTag(R.integer.btn_minus_view, itemView);

Following is the onClick method for Plus button

 View tempview = (View) btn_plus.getTag(R.integer.btn_plus_view);
 TextView tv = (TextView) tempview.findViewById(R.id.number);
 int number = Integer.parseInt(tv.getText().toString()) + 1;
 tv.setText(String.valueOf(number));
 MainActivity.modelArrayList.get(getAdapterPosition()).setNumber(number);

Following is the onClick method for Minus button

View tempview = (View) btn_minus.getTag(R.integer.btn_minus_view);
TextView tv = (TextView) tempview.findViewById(R.id.number);
int number = Integer.parseInt(tv.getText().toString()) - 1;
tv.setText(String.valueOf(number));
MainActivity.modelArrayList.get(getAdapterPosition()).setNumber(number);

Step 8: Making NextActivity

Create a new activity named “NextActivity

Add following source code into NextActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class NextActivity extends AppCompatActivity {

    private TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_next);

        tv = (TextView) findViewById(R.id.tv);

        for (int i = 0; i < 5; i++) {
            String text = tv.getText().toString();
            tv.setText(text + MainActivity.modelArrayList.get(i).getFruit()+" -> "+MainActivity.modelArrayList.get(i).getNumber()+"\n");
        }
    }
}

Paste following code into activity_next.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.exampledemo.parsaniahardik.listview_with_button_demonuts.NextActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#000"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="20dp"/>

</RelativeLayout>

Step 9: Finally Update activity_main.xml and MainActivity.java

Updating activity_main.xml

Make following code into activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.exampledemo.parsaniahardik.listview_with_button_demonuts.MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:layout_marginTop="15dp"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal">

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:id="@+id/next"
            android:text="Next Activity"/>
    </LinearLayout>
</LinearLayout>

Updating MainActivity.java

Copy following into MainActivity.java

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    public static ArrayList<Model> modelArrayList;
    private CustomAdapter customAdapter;
    private Button btnnext;
    private String[] fruitlist = new String[]{"Apples", "Oranges", "Potatoes", "Tomatoes","Grapes"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView = (RecyclerView) findViewById(R.id.recycler);
        btnnext = (Button) findViewById(R.id.next);

        modelArrayList = getModel();
        customAdapter = new CustomAdapter(this);
        recyclerView.setAdapter(customAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));

        btnnext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,NextActivity.class);
                startActivity(intent);
            }
        });
    }

    private ArrayList<Model> getModel(){
        ArrayList<Model> list = new ArrayList<>();
        for(int i = 0; i < 5; i++){

            Model model = new Model();
            model.setNumber(1);
            model.setFruit(fruitlist[i]);
            list.add(model);
        }
        return list;
    }
}

Please share this tutorial with friends.

Your sharing will help other in their path to android development.

Also you can use the comment section for any queries.

So all for RecyclerView Button Android tutorial.

Thank you.

Download Source Code for RecyclerView Button Android example

[sociallocker] Download recycler_button_code[/sociallocker]