in my app I have nested PreferencesScreen's
<PreferencesScreen>
<PreferencesScreen android:key="application">
</PreferencesScreen>
</PreferencesScreen>
Now I want to fire Intent
to take me from currrent Activity
directly to application preferences subscreen. How can I do this?
In my application I have the similar task to show second-level PreferencesScreen
programmatically. What I did:
In preferences.xml
I assigned a key to PreferencesScreen
I want to show (as shown in the question).
To show PreferencesScreen
I wrote:
final Intent preferencesActivity = new Intent(getBaseContext(), MyPreferencesActivity.class);
preferencesActivity.putExtra("PREFERENCE_SCREEN_KEY", "key_of_preference_screen_to_show");
startActivity(preferencesActivity);
Then in my PreferenceActivity class in method onCreate
the following code was added:
final Intent intent = getIntent();
final String startScreen = intent.getStringExtra("PREFERENCE_SCREEN_KEY");
if (startScreen != null) {
getIntent().removeExtra("PREFERENCE_SCREEN_KEY");
final Preference preference = findPreference(startScreen);
final PreferenceScreen preferenceScreen = getPreferenceScreen();
final ListAdapter listAdapter = preferenceScreen.getRootAdapter();
final int itemsCount = listAdapter.getCount();
int itemNumber;
for (itemNumber = 0; itemNumber < itemsCount; ++itemNumber) {
if (listAdapter.getItem(itemNumber).equals(preference)) {
preferenceScreen.onItemClick(null, null, itemNumber, 0);
break;
}
}
}
One remark... Not only second-level PreferencesScreen
, but the whole preferences hierarchy was loaded here. So, if you press Back
button, the first (parent) PreferencesScreen
will appear. In my case that was exactly what I needed. Not sure about yours.
Here is a way of handling the problem by grabbing the child-screen up front:
public class MyChildPreferenceActivity extends PreferenceActivity {
private String screenKey = "myChildScreenKey";
@Override
public PreferenceScreen getPreferenceScreen() {
PreferenceScreen root = super.getPreferenceScreen();
if (root != null) {
PreferenceScreen match = findByKey(root, screenKey);
if (match != null) {
return match;
} else {
throw new RuntimeException("key " + screenKey + " not found");
}
} else {
return null;
}
}
private PreferenceScreen findByKey(PreferenceScreen parent, String key) {
if (key.equals(parent.getKey())) {
return parent;
} else {
for (int i = 0; i < parent.getPreferenceCount(); i++) {
Preference child = parent.getPreference(i);
if (child instanceof PreferenceScreen) {
PreferenceScreen match = findByKey((PreferenceScreen) child, key);
if (match != null) {
return match;
}
}
}
return null;
}
}
// ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With