在onClick中获取产品唯一ID(查看v)

时间:2017-03-03 01:34:29

标签: android

我想在ProductListAdapter中传递产品的唯一ID,这样当我点击listview Item时,我会在onclickListener上获得它的唯一ID。

public class ProductListAdapter extends ArrayAdapter<Product>{

    private List<Product> products;

    public ProductListAdapter(Context context, int resource, List<Product> objects) {
        super(context, resource, objects);
        products = objects;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).
                    inflate(R.layout.list_item, parent, false);
        }

        Product product = products.get(position);

        TextView nameText = (TextView) convertView.findViewById(R.id.nameText);
        nameText.setText(product.getName());

        nameText.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                //I want to get the unique ID here.
                //I want to call products.getUID() here

            }
        });

        NumberFormat formatter = NumberFormat.getCurrencyInstance();
        String price = formatter.format(product.getPrice());
        TextView priceText = (TextView) convertView.findViewById(R.id.priceText);
        priceText.setText(price);

        return convertView;
    }

}

在上面的代码中,我传递了产品名称&amp;价钱。两者都是观点的一部分。所以没问题。

获取产品unique_ID

products.getUID()

但我在模型中的unique_id不是视图的一部分。我希望在onclickListener中可以访问unique_id。但是,onclickListener只有视图为pram。

setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {

    //I want to get the unique ID here.
    //I want to call products.getUID() here

    }
});

那么这里的解决方案是什么

1 个答案:

答案 0 :(得分:0)

如果您使用ListView,则可以执行以下操作

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
  @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    productlist.get(position).getUID();
  }
});