/ Custom view with button in ArrayAdapter

Custom view with button in ArrayAdapter

I have defined a custom view (xml) for my `ArrayAdapter` for a `ListView`, which adds a `Button`. I’d like to create an `OnClickListener` for this `Button` per row, yet without creating a custom adapter. Is that possible, or does Android force me to create a custom `ArrayAdapter` for my `ListView`?

Here’s a snippet of what I’m doing:

glAdapter = new ArrayAdapter(getActivity(), R.layout.fragment_grouprow, R.id.groupRowText, ListOfGroups); ListView groupListView = (ListView)mainView.findViewById(R.id.listViewGroupMain); groupListView.setAdapter(glAdapter); groupListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // Call function } });

Now I’d like to add an OnClickListener for the Button in my custom view.

Thanks in advance,


You have to implement you own Adapter & in `getView()` method set `OnClickListener` on your button. Here kick off example:

public class CustomAdapter extends ArrayAdapter { private ListView listView; public CustomAdapter(Context context, int textViewResourceId, Integer[] objects, ListView listView) { super(context, textViewResourceId, objects); this.listView = listView; } static class ViewHolder { TextView text; Button btn; } @Override public View getView(final int position, View convertView, ViewGroup parent) { Integer color = getItem(position); View rowView = convertView; if (rowView == null) { LayoutInflater inflater = ((Activity) getContext()).getLayoutInflater(); rowView = inflater.inflate(R.layout.list_view_row, parent, false); ViewHolder h = new ViewHolder(); h.text = (TextView) rowView.findViewById(R.id.item_text); h.btn = rowView.findViewById(R.id.btn); rowView.setTag(h); } ViewHolder h = (ViewHolder) rowView.getTag(); h.text.setText(color); h.indicator.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // DO what you want to recieve on btn click there. } }); return rowView; } }

ViewHolder here for optimization. You can read approximately this there.