Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
308 views
in Technique[技术] by (71.8m points)

android - How to extract the text from the selected item on the listView

I have a listview with some items. I would like to get the text from the selected item.

Here is my list adapter and the onItemClickListener:

ListView lv = (ListView)findViewById(R.id.listView1);
    lv.setAdapter(new ArrayAdapter<Country>(
            this,R.layout.list_black_text,R.id.list_content, values));


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

Could you tell me please how to get the String from the selected item.

the method ((TextView) view).getText() does not work, i have a

ClassCastException: android.widget.LinearLayout

I have found the solution, maybe somebody will need it:

ListView lv = (ListView)findViewById(R.id.listView1);
    lv.setAdapter(new ArrayAdapter<Country>(
            this,R.layout.list_black_text,R.id.list_content, values));

    lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {
            TextView textView = (TextView) view.findViewById(R.id.list_content);
            String text = textView.getText().toString(); 
            System.out.println("Choosen Country = : " + text);

    }});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use this:

String selectedFromList = (String) (lv.getItemAtPosition(position));

Whatever the datatype you are having in your list, cast accordingly.

Hope it will help. :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...