编程语言
首页 > 编程语言> > java – 无法在ListView上的自定义ArrayAdapter中获取Selected Item Index

java – 无法在ListView上的自定义ArrayAdapter中获取Selected Item Index

作者:互联网

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

解决方法:

尝试使用以下代码行:

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

                                            }
                                        });

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

标签:selecteditem,android,java
来源: https://codeday.me/bug/20190729/1567464.html