简体   繁体   中英

"android.widget.LinearLayout" cannot be cast to "android.widget.TextView" in the ListView onItemClick

I'm trying to put in a Toast the selected value from ListView .

listView1.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> a, View v, int pos, long id){
          // Now you have the id, you can set the background colour.
         Toast.makeText(getBaseContext(),((TextView)v).getText(), Toast.LENGTH_LONG).show();
    }
});

The error I get:

Error: android.widget.LinearLayout cannot be cast to android.widget.TextView

If your ListView row layout doesn't contain only a TextView you'll get that exception(the TextView can't be wrapped with a LinearLayout or something else). Instead you could do this:

public void onItemClick(AdapterView<?> a, View v, int pos, long id){
    LinearLayout parent = (LinearLayout) v;
    TextView t = (TextView) parent.findViewById(R.id.the_id_of_the_textview);
    Toast.makeText(getBaseContext(), t.getText(), 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