2

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

1 Answer 1

4

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();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.