简体   繁体   中英

Get a single field from multi-column ListView using SimpleAdapter

I have a ListActivity in which i have used a SimpleAdapter to create a list which has 2 fields. The pair of values are stored using a Map, and the list is an ArrayList. I have an onItemClickListener for this. On selecting a list entry, i get the pair ie the 2 values. I need to get only 1 of those values.

For example, if the list item is "John", "123". I want to store "123" in a string after selecting the entry from the list Any help?

Here's the code snippet:

        ListView lv = getListView();
        ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();

        list.add(putData(scanned_name, scanned_addr));

        String[] from = { "name", "address" };
        int[] to = { android.R.id.text1, android.R.id.text2 };

        SimpleAdapter adapter = new SimpleAdapter(getApplicationContext(), list,
                android.R.layout.simple_list_item_2, from, to);
        setListAdapter(adapter);

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


                Toast.makeText(getApplicationContext(),
                        parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
            }

        });

You have to catch the content of android.R.id.text1 or android.R.id.text2 . So, in your onItemClick(...) you have to do:

TextView v = (TextView)findViewById(R.id.text1);
TextView v1 = (TextView)findViewById(R.id.text2);
String content1=v.getText().toString();
String content2=v2.getText().toString();

and you can manage them as you want, even within a Toast:

Toast.makeText(getApplicationContext(),v.getText().toString(),Toast.LENGTH_LONG).show();

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