Search code examples
androidandroid-listviewandroid-event

Can't get ListView item selected


I am trying to learn how to receive a notification on a click on a radio button in a ListView but nothing comes back when I click on a radio button next to a ListView item. Below is the code where I set up the listener. I am doing this in an asynchronous task under the onPostExecute() method where I populate my ListView from the server and my main activity extends MapActivity. Does anyone know what I am doing wrong?

protected void onPostExecute(ArrayList<String> result) {
    // ... some code
    mapView.postInvalidate();

    final ArrayAdapter<String> arrayAdpt = new ArrayAdapter<String>(
            getApplicationContext(), android.R.layout.simple_list_item_single_choice,
            viewline);

    ListView restaurant_list = (ListView) findViewById(R.id.list);
    restaurant_list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    restaurant_list.setAdapter(arrayAdpt);
    restaurant_list.setScrollContainer(true);
    restaurant_list.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View arg1,
                int arg2, long arg3) {
            // TODO Auto-generated method stub
            Log.e("listargs", (String.valueOf(arg1)) + " " + String.valueOf(arg3));
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub
        }
    });

Solution

  • Does anyone know what I am doing wrong?

    I recommend to you use OnItemClickListener instead of OnItemSelectedListener

    list.setOnItemClickListener(new OnItemClickListener() {
       public void onItemClick(AdapterView<?> adapter, View parent,
                               int position, long id) {
          // do your stuff
    
       }                
    });
    

    OnItemClickListener is usually used when you want to catch click events. OnItemSelectedListener is on the other side usually used with Spinner.