3

我的 Android 项目有问题,因为我无法使用自己的 ArrayAdapter 从列表中获取选定的项目索引。我尝试了一些教程中的示例,但它们不起作用。解决办法是什么?

适配器

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

2 回答 2

10

尝试使用这行代码:

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

                                            }
                                        });

希望您能从选定的列表视图中获得准确的位置。如果您有任何问题,请通知我。希望这会奏效。

于 2013-05-22T11:32:33.597 回答
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);
于 2013-05-22T11:31:51.373 回答