Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android single choice list selection problem?

friends,

i am using following code to display list with radio buttons now i want to select specific radio button of list by default so using setSelection property which does not work.

final String [] items=new String[]{"Item1","Item2","Item3","Item4"};
            ArrayAdapter<string> ad=new ArrayAdapter<string>(this,android.R.layout.simple_list_item_single_choice,items);
            list=(ListView)findViewById(R.id.List);
            list.setAdapter(ad);

list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
list.setSelection(2);
    list.setOnItemClickListener(new OnItemClickListener()
            {

       public void onItemClick(AdapterView arg0, View arg1, int arg2,
         long arg3) {
        // TODO Auto-generated method stub
        TextView txt=(TextView)findViewById(R.id.txt);
        txt.setText(list.getItemAtPosition(arg2).toString());


       }

            }
            );

please guide what mistake am i doing?

like image 613
UMAR-MOBITSOLUTIONS Avatar asked Nov 03 '10 08:11

UMAR-MOBITSOLUTIONS


2 Answers

You'r looking for:

list.setItemChecked(2, true);
like image 71
Larphoid Avatar answered Nov 15 '22 12:11

Larphoid


I might be completely off, but I think setSelection doesn't necessarely checks your item (as in checkbox, or radio), it navigates to it though.

As a workaround (maybe there is a more elegant solution) you can extend ArrayAdapter and set checked manually in a getView() method.

Add something like this to your class:

private static class MArrayAdapter extends ArrayAdapter<String> {
    public Adapter(final Context context, final String[] objects) {
        super(context, android.R.layout.simple_list_item_single_choice, objects);
    }

    @Override
    public View getView(final int position, final View convertView, final ViewGroup parent) {
        final CheckedTextView view = (CheckedTextView) super.getView(position, convertView, parent);
        view.setChecked(position == 2);
        return view;
    }

}

And change your way of getting an adapter to new MArrayAdapter(this, items);

P.S. On my previous comment, my mistake, you better call setChoiceMode (it's just in my app, I call notifyDataSetChanged, so I don't really need it). I think your'r up to some weird behaviour without choice mode.

like image 41
Alex Orlov Avatar answered Nov 15 '22 11:11

Alex Orlov