Home » Android » Get data from custom ListView item on button click

Get data from custom ListView item on button click

Posted by: admin November 1, 2017 Leave a comment

Questions:

I wanted to add a simple button to each item in a ListView. In order to achieve this I created a custom layout and class for that ListView.

XML (listview_search_result.xml):

<?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:weightSum="4"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/lv_sr_item"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:layout_marginStart="8dp"
        android:textSize="18sp"
        android:textStyle="bold" />

    <Button
        android:id="@+id/lv_sr_btn_add"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="18dp"
        android:layout_weight="1"
        android:minHeight="0dp"
        android:text="Add"
        android:textSize="12sp" />
</LinearLayout>

Class (ListViewSearchResult.java):

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.ListAdapter;
import android.widget.TextView;
import java.util.ArrayList;

class ListViewSearchResult extends BaseAdapter implements ListAdapter {

    private ArrayList<String> list = new ArrayList<>();
    private Context context;

    ListViewSearchResult(ArrayList<String> list, Context context) {
        this.list = list;
        this.context = context;
    }

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

    @Override
    public Object getItem(int pos) {
        return list.get(pos);
    }

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

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        View view = convertView;
        if (view == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.listview_search_result, null);
        }

        TextView listItemText = (TextView)view.findViewById(R.id.lv_sr_item);
        listItemText.setText(list.get(position));

        Button addBtn = (Button)view.findViewById(R.id.lv_sr_btn_add);
        addBtn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                //Do something here??
            }
        });

        return view;
    }

}

Here is how I apply the above code in an activity:

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

    returnList = new ArrayList<>();     //I wish to add the text from the ListView item to this list.

    ArrayList<String> list = new ArrayList<>();
    ListView lv = (ListView)findViewById(R.id.ListView_searchResultList);
    ListViewSearchResult listAdapter = new ListViewSearchResult(list, this);      //Use custom class to inflate custom layout
    lv.setAdapter(listAdapter);
    //other stuff..
}

This all works fine. I can see each item properly in the ListView, and each of them has a button that says “Add”. -All good so far.

The issue is: I need to take the text from the item and return it to the current activity somehow whenever the user clicks the “Add” button.

Answers:
  1. add a callback interface in ListViewSearchResult.java.
public interface OnAddListener {
    public void onAdd(int position, String text);
}
  1. add a setter method in Adapter class (ListViewSearchResult.java).
private OnAddListener onAddListener;
public void setOnAddListener(OnAddListener listener) {
    this.onAddListener = listener;
}
  1. post the Click when the AddBtn is clicked. (ListViewSearchResult.java)
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    View view = convertView;
    if (view == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.listview_search_result, null);
    }

    final TextView listItemText = (TextView)view.findViewById(R.id.lv_sr_item);
    listItemText.setText(list.get(position));

    Button addBtn = (Button)view.findViewById(R.id.lv_sr_btn_add);
    addBtn.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            onAddListener.onAdd(position, listItemText.getText().toString());
        }
    });

    return view;
}
  1. Get the onAdd event in Activity.
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.searchresult_layout);

    returnList = new ArrayList<>();     //I wish to add the text from the ListView item to this list.

    ArrayList<String> list = new ArrayList<>();
    ListView lv = (ListView)findViewById(R.id.ListView_searchResultList);
    ListViewSearchResult listAdapter = new ListViewSearchResult(list, this);      //Use custom class to inflate custom layout
    lv.setAdapter(listAdapter);

    listAdapter.setOnAddListener(new ListViewSearchResult.OnAddListener() {
        @Override
        public void onAdd(int position, String text) {
            // do something ...
        }
    });
}