简体   繁体   中英

How to pass text of ListView item to another activity?

I made a String array which I used to populate a listview in main activity. Now I want to pass the text of the list item to another activity when I click on any list item. For example if I have an array:

String[] names = {"alfred","james","chris","jason"};

A list is populated by these names as:

alfred
james
chris
jason

and if I click on say james, then this should be passed to another activity and be printed in a textview. Please also tell me how to receive that value on the second activity.

I use ArrayList instead, is more optimized

ArrayList<String> list = new ArrayList<>();
list.add("yourstring");
list.add("yourstring");
list.add("yourstring");


yourListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent it = new Intent(this, Activity.class);
                it.putExtra("YourKeyHere", list.get(position));
                startActivity(intent);
            }
        });
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(this, YourActivity.class);
                intent.putExtra("TEXT", names[position]);
                startActivity(intent);
            }
        });

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