I have problem with my Android project, because I can't get selected item index from my List with my own ArrayAdapter. I've tried few examples from tutorials but they don't work. What is the solution?
public class myProductAdapter extends ArrayAdapter<myProductsGroup> {
private List<myProductsGroup> productList;
private Context context;
public myProductAdapter(List<myProductsGroup> productList, Context ctx) {
super(ctx, R.layout.list_products_row, productList);
this.productList = productList;
this.context = ctx;
}
@Override
public int getCount() {
return productList.size();
}
/*
public void onClick(View v) {
int position = Integer.parseInt((String) v.getTag());
OrderFirstGridPage.setSelectedItem(position);
}
*/
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_products_row, parent, false);
}
TextView tv = (TextView) convertView.findViewById(R.id.title);
tv.setTag(""+position);
TextView distView = (TextView) convertView.findViewById(R.id.description);
distView.setTag(""+position);
tv.setText("aa");
return convertView;
}
}
lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(new myProductAdapter(setupArrayProductList((ArrayList<myProduct>) ProductList), OrderFirstGridPage.this));
lv.setSelector(R.drawable.selector_for_position_list);
Try to use this line of code:
lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(new myProductAdapter(setupArrayProductList((ArrayList<myProduct>) ProductList), OrderFirstGridPage.this));
lv.setSelector(R.drawable.selector_for_position_list);
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
Log.d("My POSITION",""+position);
}
});
Hope you will get the exact position from selected listview. If you get any problem, please inform me. Hope this will works.
You need to implement AdapterView.OnItemClickListener: http://developer.android.com/reference/android/widget/AdapterView.OnItemClickListener.html
public abstract void onItemClick (AdapterView<?> parent, View view, int position, long id)
There, you'll get the index of each item.
You just have to set that listener to your list:
lv.setOnItemClickListener(yourListener);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With