onItemSelected listener

2019-08-17 10:41发布

问题:

Need some help with getting the listener to work with my listview. My activity is extending activity. This could be completely wrong. I've been mixing and matching. Any help would be awesome.

 lv.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {  
       public void onItemSelected(AdapterView<?> parentView, View childView, int position,             long id) {  
           Toast.makeText(getBaseContext(), "u clicked " +      al.get(position),Toast.LENGTH_LONG).show();
            }
         }); 

回答1:

You need to get the position from the view.

This relies on you having set a type for the list (MyType), it also requires whatever type you are using has overridden the toString().

This works because the ListView is able to return a listitem at any given position, in your code you are using al, I'm guessing this is to refer to the arraylist, you need I think to get the item at that position in the listview. (lv)

lv.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {
            /* cast should be safe as listview is of MyType */
            MyType mt = (MyType) lv.getItemAtPosition(position);
            StringBuffer prompt = new StringBuffer("You Clicked : ");
            prompt.append(mt.toString());
            Toast.makeText(getApplicationContext(), prompt, Toast.LENGTH_SHORT).show();
       }