How to programmatically change the CheckBoxPreference view

How can I change the CheckBoxPreference view at runtime?

Specifically, I would like to change the CheckBoxPreference pivot depending on whether the user has checked the checkbox or not.

If it was a normal view, I could do something like:

view1 = (TextView)findViewById(R.id.idView1);
view1.setText("some text");

      

But CheckBoxPreference has no ID, so I don't know how to get the "handle".

0


source to share


3 answers


I have an answer to my own question. The key is to use findPreference

in PreferenceActivity

as shown below:

public class MyPreferenceActivity extends PreferenceActivity{

    private SharedPreferences preferences;
    private SharedPreferences.OnSharedPreferenceChangeListener prefListener;
    private CheckBoxPreference pref;

    @Override    
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);

        pref = (CheckBoxPreference) findPreference(res.getString(R.string.keyAccount));
        pref.setSummary("something");

        //-- preference change listener
        prefListener = new SharedPreferences.OnSharedPreferenceChangeListener(){
             public void onSharedPreferenceChanged(SharedPreferences prefs, String key){  
                 if (key.equals(somekey)){                                       
                     pref.setSummary("something new");

                 }
             }
        };
        preferences.registerOnSharedPreferenceChangeListener(prefListener);     
    }

      



This has been tested and works.

+5


source


You have to use (in your XML layout file):



android:summaryOff
android:summaryOn

      

+1


source


You can set id to CheckBoxPreference using android:id

in xml for example code below

<CheckBoxPreference
        android:key="pref_boot_startup"
        android:title="Auto start"
        android:defaultValue="true"
        android:id="@+id/my_CheckBoxPref"
        />

      

To extract you can use

CheckBoxPreference check = (CheckBoxPreference)findViewById(R.id.my_CheckBoxPref);

      

-2


source







All Articles