Sebastian Sebastian - 11 days ago 6
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(R.id.listView);
adapter = new SimpleCursorAdapter(this, R.layout.list, cursor, from, to, 0);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

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

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

intent.putExtras(dataBundle);
startActivity(intent);
}
});


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

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

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

        }
}

Now poplate the String Array from the cursor