user1078725
user1078725

Reputation: 1

how to set the listview onclick?

when I run the app and click the listview, throws an Exception like this:

12-03 07:57:34.258: E/AndroidRuntime(681): java.lang.ClassCastException: android.widget.RelativeLayout

the main code is:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    this.setTitle("BaseAdapter for ListView");
    listView = (ListView) this.findViewById(R.id.MyListView);
    listView.setAdapter(new ListViewAdapter(titles, texts, resIds));

    listView.setClickable(true); 
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            Toast.makeText(getApplicationContext(),
                    ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
        }
    });

}

Upvotes: 0

Views: 177

Answers (2)

Todor Kolev
Todor Kolev

Reputation: 11

Most probably you populate the list view with relative layouts, so when you click the view you get from the onItemClick method is a Relative layout. Use:

view.findViewById(R.id.your_text_view_id); 

to get a reference to the textview.

Upvotes: 1

Sunny
Sunny

Reputation: 14808

I think this line

listView = (ListView) this.findViewById(R.id.MyListView); 

is a problem

you must define your listview id as

@android:id/list 

in your xml layout file

and change above line to this one:

listView = (ListView) this.findViewById(R.id.list);

Upvotes: 0

Related Questions