Listview With Button Android Studio Example

listview with button android demonuts

Hello, In this listview with button android tutorial, you will learn how to use a button in listview item.

We will see how to handle button’s click listeners in every row item of listview.

I have created listview elements with multiple clickable buttons in this tutorial example.

There are some problems like

  • You click on first button, but system clicks on last button
  • Quantity number of item change when scroll the listview.

Implementing button in the listview is a little complex task.

But you can do it smoothly if you follow proper method with the efficient code snippets.

Getting the proper position of clicked button and set onclick event for button required some additional coding lines.

I will go through all these problems and teach you how to solve them easily.

First of all check out the output of this example, so that you can have an idea what we are developing at the end of the tutorial.

Wait for one minute

If you have not basic idea about listview and adapter, check out listview with image and text tutorial first.

Check listview with checkbox android example for gaining knowledge about how to use a checkbox in listview row.

Creating Listview With Button Android Example

Step 1: Create a new project in the android studio.

Empty Activity is the option, you need to select when creating a new project in the android studio.

Step 2: Updating activity_main.xml file

Add following code into activity_main.xml file

<?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">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:id="@+id/lv"/>
        <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>

Step 3: Creating Model.java class

Create a new class named Model.java and add following

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;
    }
}

This class represents the various methods to set and get the data in the adapter class.

Objects of this class will be used to maintain the proper data structure.

Step 4: Creating Integer Resource File

In this tutorial, we need to create integer resources.

Integer resources are same as string resources which are written at string.xml file in values directory.

To define integer resources, we need to create integer.xml file in values directory.

To create integer.xml file, right click on values folder -> New -> Value resource file

listview with button android integer
Directory for integer.xml

Copy following code in an integer.xml file

<?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 5: Creating row layout for listview

Create one layout resource file and name it as lv_item.xml and copy below code

<?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="match_parent"
    android:orientation="vertical">

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


        <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:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/number"
            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:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/plus"
            android:layout_marginLeft="20dp"
            android:text="Plus"
            android:textColor="#000" />

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

This layout file says us how every row of the listview will be look a like.

  • Mainly two textviews and two buttons are present in this file. One button will increase the fruit quantity and the other one decrease it.
  • One textview represnts the name of the fruit.
  • Other textview shows the quantity of that fruit in terms of numbers.

Step 6: Creating CustomAdapter.java class:

Create new java class named CustomAdapter and add following code

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

/**
 * Created by hardik on 9/1/17.
 */
public class CustomAdapter  extends BaseAdapter {

    private Context context;


    public CustomAdapter(Context context) {

        this.context = context;
    }

    @Override
    public int getViewTypeCount() {
        return getCount();
    }
    @Override
    public int getItemViewType(int position) {

        return position;
    }

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

    @Override
    public Object getItem(int position) {
        return MainActivity.modelArrayList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;

        if (convertView == null) {
            holder = new ViewHolder(); LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.lv_item, null, true);


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

            convertView.setTag(holder);
        }else {
            // the getTag returns the viewHolder object set as a tag to the view
            holder = (ViewHolder)convertView.getTag();
        }

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


        holder.btn_plus.setTag(R.integer.btn_plus_view, convertView);
        holder.btn_plus.setTag(R.integer.btn_plus_pos, position);
        holder.btn_plus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                View tempview = (View) holder.btn_plus.getTag(R.integer.btn_plus_view);
                TextView tv = (TextView) tempview.findViewById(R.id.number);
                Integer pos = (Integer) holder.btn_plus.getTag(R.integer.btn_plus_pos);

                int number = Integer.parseInt(tv.getText().toString()) + 1;
                tv.setText(String.valueOf(number));

                MainActivity.modelArrayList.get(pos).setNumber(number);

            }
        });

        holder.btn_minus.setTag(R.integer.btn_minus_view, convertView);
        holder.btn_minus.setTag(R.integer.btn_minus_pos, position);
        holder.btn_minus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                View tempview = (View) holder.btn_minus.getTag(R.integer.btn_minus_view);
                TextView tv = (TextView) tempview.findViewById(R.id.number);
                Integer pos = (Integer) holder.btn_minus.getTag(R.integer.btn_minus_pos);

                int number = Integer.parseInt(tv.getText().toString()) - 1;
                tv.setText(String.valueOf(number));

                MainActivity.modelArrayList.get(pos).setNumber(number);

            }
        });

        return convertView;
    }

    private class ViewHolder {

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

    }

}
  • We are using an arraylist which is defined in the Main Activity.
  • This arraylist gives the data information to populate the listview.
  • Every object of the arraylist have value for fruit name and the quantity number.
  • Quantity number is changing with respect to the click event of plus and minus buttons.

Step 7: Setting tag for position and convertView

Look at this code

 holder.btn_plus.setTag(R.integer.btn_plus_view, convertView);
 holder.btn_plus.setTag(R.integer.btn_plus_pos, position);

When listview is populating, we can set tags for postion and views as per above code.

We have set tags on btn_plus for position and converView.

setTag(key,value) method is used for this.

key for tag is used from the integer.xml file, we created earlier.

Your key should be unique for setting each tag.

Step 8: Getting tags in buttons onClick() method

 holder.btn_plus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                View tempview = (View) holder.btn_plus.getTag(R.integer.btn_plus_view);
                TextView tv = (TextView) tempview.findViewById(R.id.number);
                Integer pos = (Integer) holder.btn_plus.getTag(R.integer.btn_plus_pos);

                int number = Integer.parseInt(tv.getText().toString()) + 1;
                tv.setText(String.valueOf(number));

                MainActivity.modelArrayList.get(pos).setNumber(number);

            }
        });
  • You can get position and converView by using getTag(key) method.
  • We are setting tempview with view got from getTag() method.
  • In getTag() method we are using same key, which we used in setTag() method.
  • Similarly we can get position also using getTag() method and proper key.
  • Here tempview is a whole row view which contains two textView and two button.

You can inflate views of row view and set values to them. Here we are setting textView’s value by following code

 tv.setText(String.valueOf(number));
  • Similarly, for btn_minus, all tags are set and get and values of textView are updated.

Step 9: Creating NextActivity

To open new activity in android studio, click on File tab which is present at the left top bar.

Now go to File->New->Activity->Empty Activity and give name of activity as NextActivity.

listview with button android next activity

Step 10: Updating NextActivtiy code

Add 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>

Add following into NextActivity.java class

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");
        }
    }
}

Step 11: Updating MainActivity.java class

Put below code in MainActivity.java

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private ListView lv;
    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);

        lv = (ListView) findViewById(R.id.lv);
        btnnext = (Button) findViewById(R.id.next);

        modelArrayList = getModel();
        customAdapter = new CustomAdapter(this);
        lv.setAdapter(customAdapter);

        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;
    }
}

Consider the below code

 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;
    }

getModel() method creates an arraylist with the objects of the Model class.

This arraylist works as a data provider for the listview adapter.

Number of objects in the arraylist is equals to the number of rows in the listview.

So it was all about implementing listview with button android feature in our android app programmatically. Thank you and keep coding!

Download Source Code for listview with button android tutorial

[sociallocker] Download Demo [/sociallocker]