简体   繁体   English

如何将特定项目故意放入ListView中?

[英]How do I put a specific item in my ListView in an intent?

ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this,
            android.R.layout.simple_list_item_1, values);
    // setListAdapter(adapter);

    final ListView listView = (ListView) findViewById(R.id.list);
    listView.setAdapter(adapter);

    listView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {

    });

How do I get the item in the listview that was clicked and store it in an intent (I know how to store it in an intent, i just need to get the item that was clicked)? 如何在单击的列表视图中获取项目并将其存储在意图中(我知道如何将其存储在意图中,我只需要获取被单击的项目)?

您应该在OnItemClickListener中使用getItem()方法:

adapter.getItem(position);

After you implement the OnItemClickListener interface: 在实现OnItemClickListener接口之后:

public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
    Intent intent = new Intent(getActivity(), NextActivity.class);

    //since you have your values inside an array; you can use position to get
    //the selected value

    intent.putExtra("KEY", values.get(position));

    startActivity(intent);
}

I hope this helped! 希望对您有所帮助!

I assume you already coded the part of the Adapter for the ListView. 我假设您已经为ListView编码了适配器的一部分。 In this adapter, there are some methods that will allow you to manipulate your list and therefore, each item of your list. 在此适配器中,有些方法将允许您处理列表,因此可以操作列表的每个项目。 You can use this method in the adapter 您可以在适配器中使用此方法

public String getItem(int index) {

    return getItem(index);
}

Note that it can return the item that you're looking for (integer, long, object...). 请注意,它可以返回您要查找的项目(整数,长整数,对象...)。 You must extend your adapter to BaseAdapter or another class in order for these methods to appear 您必须将适配器扩展到BaseAdapter或其他类,才能显示这些方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM