问题
How can I change the view of a CheckBoxPreference at runtime?
Specifically, I'd like to change a CheckBoxPreference summary depending on whether the user has checked the box or not.
If it were a normal view, I could do something like:
view1 = (TextView)findViewById(R.id.idView1);
view1.setText("some text");
But a CheckBoxPreference has no id, so I don't know how to get a "handle" to it.
回答1:
I have an answer to my own question. The key is to use findPreference
in a PreferenceActivity
, as follows:
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 is tested and works.
回答2:
You should use (in XML layout file):
android:summaryOff
android:summaryOn
回答3:
You can set id to CheckBoxPreference using android:id
in xml like code below
<CheckBoxPreference
android:key="pref_boot_startup"
android:title="Auto start"
android:defaultValue="true"
android:id="@+id/my_CheckBoxPref"
/>
To retrieve you can use
CheckBoxPreference check = (CheckBoxPreference)findViewById(R.id.my_CheckBoxPref);
来源:https://stackoverflow.com/questions/8656203/how-to-programatically-modify-a-checkboxpreference-view