1

I have set lp.setDefaultValue("2"), but when I run the app, I find the 2th item isn't selected, why? Thanks!

public class PhotoPreference extends PreferenceActivity{
     @Override
     protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            addPreferencesFromResource(R.xml.mypreference);

            setContentView(R.layout.photo_preference);

            // Look up the AdView as a resource and load a request.
            AdView adView = (AdView)this.findViewById(R.id.adViewpreference);
            adView.loadAd(new AdRequest());

            ListPreference lp = (ListPreference)findPreference("SetLastFolder");            
            CharSequence[] entries = { "One", "Two", "Three" };
            CharSequence[] entryValues = { "1", "2", "3" };

            lp.setEntries(entries);
            lp.setEntryValues(entryValues);

            lp.setDefaultValue("2");      


     }

}



<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
    android:key="AppPreference"
    android:summary="@string/Preferencesummary"
    android:title="@string/Preference" >   

    <ListPreference    
        android:key="SetLastFolder"
        android:dialogTitle="@string/SelectGallery"
        android:title="@string/SelectGallery"
        android:summary="@string/SelectGallerysummary"        
        android:layout="@layout/photopreference_layout" 
     />

</PreferenceScreen>
HelloCW
  • 843
  • 22
  • 125
  • 310

1 Answers1

4

Try setValueIndex() instead of setDefaultValue().

See this question

So if you change...

lp.setDefaultValue("2");

to...

lp.setValueIndex(int index); // pass the appropriate index

then it should work.

Updated
I hope defaultvalue is locate the index 1 only when a user have not do any choice!

For this, you can check if lp is null first and then set the defaultvalue...

if(lp.getValue() == null) {
   lp.setValueIndex(1);
}
Community
  • 1
  • 1
neo108
  • 5,156
  • 3
  • 27
  • 41
  • Thanks! but it's not what I want. If lp.setValueIndex(1), the app always locate the index 1, I hope defaultvalue is locate the index 1 only when a user have not do any choice! – HelloCW Jul 22 '13 at 03:19
  • You can check if `lp` is `null` first and then set the defaultvalue. See my updated answer. Hope this helps! – neo108 Jul 22 '13 at 03:55