简体   繁体   中英

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:

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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