Sebastian Sebastian - 8 months ago 45
Android Question

How to add button function in listview

My code...

ListView listView;
SimpleCursorAdapter adapter;
mydb = new DBHelper(this);
Cursor cursor = mydb.fetch();
listView = (ListView) findViewById(;
adapter = new SimpleCursorAdapter(this, R.layout.list, cursor, from, to, 0);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

id = (TextView) arg1.findViewById(;

int id_To_Search = Integer.valueOf(id.getText().toString());

Bundle dataBundle = new Bundle();
dataBundle.putInt("_id", id_To_Search);

Intent intent = new Intent(getApplicationContext(), AddPatient.class);


I ve added a button to every list. How can i use that button as same function as the listview on item click event.? How can i use that button.?

Answer Source

First, add a Button in your list item layout. Then try to create Custom adapter instead of using SimpleCursorAdapter. Here is example of Custom Adapter

    public class MySimpleArrayAdapter extends ArrayAdapter<String> {
        private final Context context;
        private final String[] values;

        public MySimpleArrayAdapter(Context context, String[] values) {
                super(context, -1, values);
                this.context = context;
                this.values = values;

        public View getView(int position, View convertView, ViewGroup parent) {
                LayoutInflater inflater = (LayoutInflater) context
                View rowView = inflater.inflate(R.layout.list, parent, false);
                TextView textView = (TextView) rowView.findViewById(;
                Button button = (Button) rowView.findViewById(;
                // change the text for your list item
                button.setOnClickListener(new View.OnClickListener() {
                      public void onClick(View view) {
                      // do whatever you want


Now poplate the String Array from the cursor