Android - how to add element click method in ArrayAdapter

I have a simple ArrayAdapter. I want to configure a listener for each click on a line in my list so that a new activity opens. How can I do it? My ArrayAdapter code is

public class CountryListAdapter extends ArrayAdapter<String> { private final Activity context; private final ArrayList<String> names; public CountryListAdapter(Activity context, ArrayList<String> names) { super(context, R.layout.rowlayout, names); this.context = context; this.names = names; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = context.getLayoutInflater(); View rowView = inflater.inflate(R.layout.rowlayout, null, true); TextView textView = (TextView) rowView.findViewById(R.id.label); textView.setText(names.get(position)); return rowView; } 
+6
source share
3 answers

Assuming you are using a ListActivity implementation of OnItemClickListener you can use this code:

 ArrayAdapter<Object> ad = new ArrayAdapter<Object>(this, android.R.layout.simple_list_item_checked, items); setListAdapter(ad); ListView list = getListView(); list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); //list.setItemChecked(0, true); list.setOnItemClickListener(this); 

EDIT: Otherwise, if you are not expanding ListActivity, use listview in your layout and replace ListView list = getListView() with something like ListView list = findViewById(R.id.listView) . Replace list.setOnItemClickListener(this) with

 list.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { } }); 
+8
source

Just implement AdapterView.OnItemClickListener.

 @Override public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) { Intent i = new Intent(this, ProductActivity.class); i.putExtra("item_id", manager.getItemIdAtIndex(pos)); startActivity(i); } 

Then just set the class with this method as onItemClickListener in your adapter.

+4
source

Once you have installed the adapter using:

 mListView.setAdapter(myCountryListAdapter); 

Then you can configure the click listener for the list:

 mListView.setOnParentClickListener(new OnClickListener() { public void onClick(View view,) { ///do what you want the click to do } }); 
-2
source

Source: https://habr.com/ru/post/901456/


All Articles