Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ListView.setSelection is not working

I am working on a dialog that has a ListView ..

I have successfully put the adapter,selector,list_itemlayout in the onCreate() as follows..

protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    setContentView(R.layout.variable_dialog);

    lv=(ListView) findViewById(R.id.VariableslistView1);
    lv.setAlwaysDrawnWithCacheEnabled(true);        
    final ArrayAdapter<String> ad=new ArrayAdapter<String>(getContext(),android.R.layout.simple_list_item_1,Program.get().symboltable.getSymbols());
    lv.setAdapter(ad);

    lv.setSelector(R.drawable.item_selected);

But whenever I try to get the getSelectedItemPosition() it alsways returns -1

as if I didn't select anything ..even if I invoke the selection my self like this:

lv.setSelected(true);
    lv.setSelection(1);
    lv.setItemChecked(1, true);
    ad.notifyDataSetChanged();
    ad.notifyDataSetInvalidated();

and here is my selector :

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
 <stroke
    android:width="2dp"
    android:color="#FF00FF00" />

<gradient
    android:angle="225"
    android:endColor="#DD2ECCFA"
    android:startColor="#DD000000" />

<corners
    android:bottomLeftRadius="7dp"
    android:bottomRightRadius="7dp"
    android:topLeftRadius="7dp"
    android:topRightRadius="7dp" />


</shape>

For god's sake what the heck is wrong?!?!

I even tried the AdapterView.OnItemSelectedListener but never succeeded :|

Can anybody tell me what is the problem .

Thanks in advance

like image 845
Zuhair Kj Avatar asked Jul 09 '26 10:07

Zuhair Kj


1 Answers

I have had same problem (not working setSelection() called immediately after notifyDataSetChanged()), this finally helped me:

    lv.post(new Runnable() {

        @Override
        public void run() {
            lv.setSelection(mSelectedPosition);
        }
    });
like image 61
Miroslav Michalec Avatar answered Jul 11 '26 23:07

Miroslav Michalec