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

后端 未结 14 2486
轻奢々
轻奢々 2020-11-28 07:55

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         


        
相关标签:
14条回答
  • 2020-11-28 08:47

    I found a simplest way:

    list_content.xml

     <TextView
        <!-- rest of the code -->
        android:id="@+id/content"
        android:onClick="get_content"  <!-- Just add this -->
        />
    

    MainActivity

    public void get_content(View view){
    
        TextView textView = view.findViewById(R.id.content);
        System.out.println("Text is: "+textView.getText().toString());
    }
    
    0 讨论(0)
  • 2020-11-28 08:48

    The other answers look good, but I thought I'd wrap everything up into one complete answer.

    There are multiple ways to achieve this and it also depends on whether you are getting text from simple listView or from Custom ListView(with custom_list_item.xml).

    For Simple ListView

    lv.setOnItemClickListener(new OnItemClickListener() {
    
        public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {
            String text = lv.get(position).tostring().trim();//first method 
            final String text = ((TextView)view).getText();// second method
    }});
    

    For Custom ListView

    lv.setOnItemClickListener(new OnItemClickListener() {
    
        public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {
            TextView textView = (TextView) view.findViewById(R.id.list_content);
    //where list_content is the id of TextView in listview_item.xml
    
    }});
    

    Problem with others Answers

    @Android Killer string Casting is missing.

    @Rishi doesn't give detail about using R.id.list_content

    0 讨论(0)
提交回复
热议问题