I'm making a backup and restore options in my android app. Then you open the preference I want a button to backup and a button to restore. I make the button in my xml/preference.xml file like this:
<PreferenceCategory android:title="Backup">
<Preference
android:key="backup"
android:title="Backup"
android:summary="Make a backup of shows"
/>
<Preference
android:key="restore"
android:title="Restore"
android:summary="Restore shows from backup"
/>
</Pr开发者_如何学CeferenceCategory>
I my preference class I implements OnSharedPreferenceChangeListener, and add getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
to onResume()
and getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
to OnPause()
.
The i implements onSharedPreferenceChanged:
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
// Let's do something when my counter preference value changes
if (key.equals("backup")) {
Toast.makeText(this, "Backup button pressed", Toast.LENGTH_SHORT).show();
} else if (key.equals("restore")) {
Toast.makeText(this, "Restore button pressed", Toast.LENGTH_SHORT).show();
}
}
But no toast is displayed then i press one of the buttons. I works fine on i.e. CheckBoxPreference, but i only need a button, not the checkbox. Some one who can help?
If it is just a simple button then there is no preference that can be changed, so your onSharedPreferenceChanged
will not be called in this case.
Use an OnClick listener instead:
OnPreferenceClickListener btnListener = new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
final String key = preference.getKey();
if (key.equals("backup")) {
// show toast
return true; // we handled the click
}
return false; // we didn't handle the click
}
};
Preference prefBtn = findPreference("backup");
prefBtn.setOnPreferenceClickListener(btnListener);
put your code to
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
Preference preference);
method. preference
here is the preference that were clicked.
精彩评论