我的Android项目有问题,因为我无法使用自己的ArrayAdapter从我的List中获取所选项目索引。我从教程中尝试了一些示例,但它们不起作用。解决方案是什么?
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);
答案 0 :(得分:6)
尝试使用以下代码:
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);
}
});
希望您能从所选列表视图中获得确切位置。如果您有任何问题,请通知我。希望这会奏效。
答案 1 :(得分:1)
您需要实现AdapterView.OnItemClickListener:http://developer.android.com/reference/android/widget/AdapterView.OnItemClickListener.html
public abstract void onItemClick (AdapterView<?> parent, View view, int position, long id)
在那里,你将获得每个项目的索引。
您只需将该侦听器设置为您的列表:
lv.setOnItemClickListener(yourListener);