单击ListView中的项目时获取项目位置0

时间:2017-09-13 13:24:53

标签: android android-intent android-adapterview

我正在尝试将商品位置从Fragment发送到Activity,但每次在listView中选择商品时,我都会收到invoiceId 0

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id)
        {
            Intent seperateView = new Intent(rootView.getContext(),SeperateViewForDeliveryList.class);
            seperateView.putExtra("invoiceId", listView.getItemAtPosition(position).toString());
            startActivity(seperateView);
        }
    });
    listView.setAdapter(deliveryListAdapter);
    return rootView;

在活动类

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_seperate_view_for_delivery_list);
    invoiceId = getIntent().getExtras().getString("invoiceId");
    Toast.makeText(this, "invoiceID " + invoiceId, Toast.LENGTH_SHORT).show();
}

4 个答案:

答案 0 :(得分:0)

我们也可以在Intent中传递整数值。试试这个:

seperateview.putExtra("invoiceId",listview.getItemAtPosition(position));
getIntent().getIntExtra("invoiceId",0);

答案 1 :(得分:0)

使用此

seperateview.putExtra("invoiceId",String.valueOf(position));

答案 2 :(得分:0)

listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id)
    {
        Intent seperateview=new Intent(rootView.getContext(),SeperateViewForDeliveryList.class);
        seperateview.putExtra("invoiceId",parent.getItemAtPosition(position).toString());
        startActivity(seperateview);
    }
});
listview.setAdapter(deliveryListAdapter);
return rootView;

试试这个

答案 3 :(得分:0)

getItemAtPosition返回与列表中指定位置关联的数据对象,而position本身就是您想要的。

将您的代码更改为

seperateView.putExtra("invoiceId", String.valueOf(position));