I've implemented my preferences like shown in the official guidelines.
I have a PreferenceActivity which creates the PreferenceFragment like this:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if (extras != null)
{
Bundle bundle = new Bundle();
_widgetID = extras.getInt(GlobalSettings.EXTRA_WIDGET_ID);
bundle.putInt(GlobalSettings.EXTRA_WIDGET_ID, _widgetID);
WidgetSettingsFragment fragment = new WidgetSettingsFragment();
fragment.setArguments(bundle);
getFragmentManager().beginTransaction().replace(android.R.id.content,
fragment).commit();
}
}
The PreferenceFragment loads the preferences from the resources and they contain a preference subscreen like this:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<!-- opens a subscreen of settings -->
<PreferenceScreen
android:key="button_voicemail_category_key"
android:title="#string/voicemail"
android:persistent="false">
<ListPreference
android:key="button_voicemail_provider_key"
android:title="#string/voicemail_provider" ... />
<!-- opens another nested subscreen -->
<PreferenceScreen
android:key="button_voicemail_setting_key"
android:title="#string/voicemail_settings"
android:persistent="false">
...
</PreferenceScreen>
<RingtonePreference
android:key="button_voicemail_ringtone_key"
android:title="#string/voicemail_ringtone_title"
android:ringtoneType="notification" ... />
...
</PreferenceScreen>
...
</PreferenceScreen>
This works well so far, but now I'd like to have an up-Button in the actionBar when the preferences subscreen is shown. Any idea how to accomplish that?
I have tried to set setDisplayHomeAsUpEnabled(true) in my activity but then the up-Button is only shown in the main preferences (where it should not) and not in the subscreen.
I'm wondering that even in the official docs the subscreen is shown without an active up-Button:
Link to the docs: Settings
Any help is really welcome
I finally got it to work :D. It's quite hacky but it works.
The problem is, that using subscreens in xml-layouts results in some 'code magic'.
A new activity/dialog is started for the subscreen and you don't have direct access to it.
To get access to the actionbar and the OnClickListener of the home/up-button you need to get a reference to your PreferenceScreen and get its parent Dialog in order to access the actionbar and its home/up button.
This is how it is done inside my PreferenceFragment:
#Override
public void onCreate(Bundle savedInstanceState)
{
...
final PreferenceScreen preferenceScreen = (PreferenceScreen) findPreference(getString(R.string.keyPrefScreenDynamicWidgetDetails));
preferenceScreen.setOnPreferenceClickListener(new OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
preferenceScreen.getDialog().getActionBar().setDisplayHomeAsUpEnabled(true);
final Dialog dialog = preferenceScreen.getDialog();
View homeBtn = dialog.findViewById(android.R.id.home);
if (homeBtn != null)
{
OnClickListener dismissDialogClickListener = new OnClickListener()
{
#Override
public void onClick(View v)
{
dialog.dismiss();
}
};
// Prepare yourselves for some hacky programming
ViewParent homeBtnContainer = homeBtn.getParent();
// The home button is an ImageView inside a FrameLayout
if (homeBtnContainer instanceof FrameLayout) {
ViewGroup containerParent = (ViewGroup) homeBtnContainer.getParent();
if (containerParent instanceof LinearLayout) {
// This view also contains the title text, set the whole view as clickable
((LinearLayout) containerParent).setOnClickListener(dismissDialogClickListener);
} else {
// Just set it on the home button
((FrameLayout) homeBtnContainer).setOnClickListener(dismissDialogClickListener);
}
} else {
// The 'If all else fails' default case
homeBtn.setOnClickListener(dismissDialogClickListener);
}
}
return true;
}
});
...
}
Following link gave me the final hints and code to solve my problem:
Action Bar Home Button not functional with nested PreferenceScreen
I do this per the Android docs in the "Supporting older versions with preference headers" section http://developer.android.com/guide/topics/ui/settings.html#BackCompatHeaders. Using the legacy PreferenceActivity, you specify a Preference in the xml that launches an intent to the same preference activity class. The activity checks the intent action and determines if it is nested or not (to show the up button) and which preference xml to inflate in the screen.
Of course, I intend to support older devices as well. I have found that the PreferenceFragment is only useful for large tablets that use preference headers.
To reuse preferences between phones and tablets I came up with this solution https://stackoverflow.com/a/20806812/1139784
To enable the up action do the following:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayUseLogoEnabled(true);
this will give you the icon.
then add
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
you can alter this to go where you need to. As another option you can use the navigateUpTo(Intent intent) and the onSupportNavigateUpTo(Intent intent) methods and specify the intent you want to return to.
Related
I'm trying to learn how to develop Android apps. I followed a video tutorial on YouTube, and it ended by adding a simple App Settings screen to the application.
However, there's one point that bothers me: when I press the back button on my phone's navigation bar, the changed settings aren't applied.
I have tried searching on Google, but none of the solutions I found have worked. The fact that I don't yet understand 100% of what's happening on the proposed solutions may also contribute to my difficulty on solving this one problem.
The behavior I expect from the app is that when I press the back button on the navigation bar, the changed settings should be applied.
For instance, I have a setting for dark background, which is controlled by a checkbox. The current behavior is: I check the setting for dark background. When I press the back button on the navigation bar, the setting isn't applied (I do have a method that loads the preferences on my MainActivity). What I want to happen is when I press the back button, the dark background is applied in this case.
From what I understand, I believe that overriding onBackPressed should do the trick, but I don't know what should be executed in order to properly apply the settings.
Here are the class and layout of my PreferenceScreen. Regarding the strings on the XML, they aren't actually hard-coded. I just copied the English values here to show the text that should appear on the interface.
public class AppPreferences extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note_detail);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
SettingsFragment settingsFragment = new SettingsFragment();
fragmentTransaction.add(android.R.id.content, settingsFragment, "SETTINGS_FRAGMENT");
fragmentTransaction.commit();
}
public static class SettingsFragment extends PreferenceFragment
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.app_preferences);
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="General">
<EditTextPreference
android:title="Notebook"
android:summary="The title that will be used on the main action bar."
android:key="title"
android:defaultValue="Notebook" />
</PreferenceCategory>
<PreferenceCategory
android:title="Color">
<CheckBoxPreference
android:title="Dark Background"
android:summary="Is the main background color dark?"
android:key="background_color"
android:defaultValue="false" />
</PreferenceCategory>
</PreferenceScreen>
You will need to use
public class AppPreferences extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_note_detail);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
SettingsFragment settingsFragment = new SettingsFragment();
fragmentTransaction.add(android.R.id.content, settingsFragment, "SETTINGS_FRAGMENT");
fragmentTransaction.commit();
}
public static class SettingsFragment extends PreferenceFragment
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.app_preferences);
Preference preference = findPreference("background_color");
preference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
//do your action here
return false;
}
});
}
}
}
Or from other activity:
PreferenceManager.setDefaultValues(this, R.xml.your_setting_xml, false);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
if (settings.getBoolean("background_color", true)) {
//do your action here
.........
Refer to this question also, (it has similar use case):
Checkbox Preference and Checking if its enabled or disable
Like #Chisko said, there isn't enough code in your question for us to be able to figure out your end goal - although I'm guessing you are wanting some form of persistent storage for your app to be able to save your app preferences. For this, you will want to use something in Android called SharedPreferences. This allows you to save simple data types to be accessed later.
Give that link a read, and then try saving/loading one simple piece of data. You'll want to load it from SharedPreferences on starting the activity (you can specify a default value if it hasn't been saved yet) and then you'll want to save the data in onBackPressed() as you said.
Best of luck and if you run into any issues, just comment here.
#Abdulhamid Dhaiban correctly points it out.
I'll add to your suggestion about overriding the onBackPressed() method.
If your "Up" button (top left <-) provides the correct result, then you can set the Back button to behave like the Up button by just adding the following code:
#Override
public void onBackPressed() {
super.onBackPressed();
NavUtils.navigateUpFromSameTask(this);
}
Hope it helps!
I'm looking for a way to display a DialogFragment in single-pane mode without creating a new activity.
I originally set up a DialogFragment as a popup dialog in my Android app, with the intent to eventually pursue the master-detail pattern for larger devices.
However, now that I'm looking to finally implement the master-detail setup I'm running into all sorts of UI complications. Basically, I'd like to have something like a 'contextual action mode' update to the action bar. That requires some planning in two-pane mode, but it doesn't work at all with a popup dialog (unless I'm missing some way to show the action bar and the popup dialog).
I'd rather not create a new activity to house the detail DialogFragment on non-tablet/large devices, since there is a lot of DB-related code in the existing activity. However, I have trouble just doing FragmentTransaction.replace because the main view is based on a modified FragmentTabsPager from the compatibility lib v4 demo. I don't have a fragment to replace, unless I wrap the entire pager in a fragment - and I'm worried that nesting fragments is a hack that will complicate, rather simplify things in the long run. Am I wrong?
I'm also using ActionBarCompat, which complicates things as there are some UI options that aren't ported. I'd consider going API 11+ if it meant finding a clean solution to this.
BTW I'm starting to look at Commonsware's master-detail library, but it's a bit of code to grok and ingest, and I think it would require a few possibly big changes to make my code compatible.
Any suggestions or comments? I think I'm too close to this one to see how to simplify it...
(1) You should definitely not have to create an entire new Activity whose sole purpose is to house a new DialogFragment. If you are going to create a new activity at all, you might as well just give it a dialog-theme and display that as your dialog instead... that would eliminate the need to show a DialogFragment entirely.
(2) Your question is a bit too general for me to give a confident answer... you mention "contextual action mode", "dialog fragment", "fragment tabs pager", "nested fragments", etc. and I'm not sure how it all fits together or what specifically you are trying to achieve. What I do know is that no matter the configuration, the host activity should always be the one in charge of performing fragment transactions (such as showing a DialogFragment) as this will significantly reduce code complexity (especially when the number of fragments displayed on the screen varies depending on the screen size). Do your fragments communicate with the activity via activity callback methods (as described here and here)? Where in your code do you show the DialogFragment: in your activity or in one of the master/detail fragments?
Try this:
This is the XML of the layout of your Activity.
What you need to do is enclose all your activity content in a layout (like i have done here in id = all_activity_content_id).
Now put two more views in the activity:- A RelativeLayout for your dialog and a View for making the background translucent.
Note: Make sure the root layout of your activity is a RelativeLayout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="in.curium.testandroid.MainActivity" >
<!-- all your activity's existing code goes here -->
<RelativeLayout
android:id="#+id/all_activity_content_id"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#android:color/holo_red_light" >
<ToggleButton
android:id="#+id/toggle_dialog_box_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:padding="10dp"
android:textOff="#string/show_dialog"
android:textOn="#string/hide_dialog" />
</RelativeLayout>
<!-- translucent black background behind the dialog -->
<View
android:id="#+id/black_layer_id"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:alpha="0.6"
android:background="#android:color/black"
android:visibility="gone" />
<!-- your dialog layout -->
<RelativeLayout
android:id="#+id/dialog_id"
android:layout_width="200dp"
android:layout_height="150dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:background="#00BFFF"
android:visibility="gone" >
<TextView
android:id="#+id/dialog_title_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#android:color/black"
android:text="#string/dialog_title"
android:textColor="#android:color/white" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/dialog_title_id"
android:text="#string/dialog_description" />
</RelativeLayout>
In your activity class add two methods to show and hide the dialog layout.
Override the back button to dismiss the dialog when visible otherwise call super.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggle_dialog_box_id);
toggleButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View toggleB) {
boolean isOn = ((ToggleButton) toggleB).isChecked();
if (isOn) {
showDialog();
} else {
hideDialog();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void showDialog() {
View opaqueBackground = findViewById(R.id.black_layer_id);
RelativeLayout dialog = (RelativeLayout) findViewById(R.id.dialog_id);
opaqueBackground.setVisibility(View.VISIBLE);
dialog.setVisibility(View.VISIBLE);
}
private void hideDialog() {
View opaqueBackground = findViewById(R.id.black_layer_id);
RelativeLayout dialog = (RelativeLayout) findViewById(R.id.dialog_id);
opaqueBackground.setVisibility(View.GONE);
dialog.setVisibility(View.GONE);
}
#Override
public void onBackPressed() {
ToggleButton toggleB = (ToggleButton) findViewById(R.id.toggle_dialog_box_id);
boolean isOn = toggleB.isChecked();
if (isOn) {
toggleB.setChecked(false);
hideDialog();
} else {
super.onBackPressed();
}
}}
Now any code that you want to put in the dialog will have access to the database adapter that you have in the activity.
Positioning the dialog in the center of your detail fragment will be a bit tricky.
Hope this helps.
Source Code: https://github.com/testv200/DialogInsideAcitvity
It's not possible Because you are using Activity
If you extends FragmentActivity than it's only possible because if you want to show DialogFragment than it's required FragmentManager reference it's not possible in normal Activity. It's provide only inside FragmentActivity or above API level 13
This is my DialogFragment class
public class DetailedFragment extends DialogFragment {
private static final String ARG_SHOW_AS_DIALOG = "DetailedFragment.ARG_SHOW_AS_DIALOG";
public static DetailedFragment newInstance(boolean showAsDialog) {
DetailedFragment fragment = new DetailedFragment();
Bundle args = new Bundle();
args.putBoolean(ARG_SHOW_AS_DIALOG, showAsDialog);
fragment.setArguments(args);
return fragment;
}
public static DetailedFragment newInstance() {
return newInstance(true);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if (args != null) {
setShowsDialog(args.getBoolean(ARG_SHOW_AS_DIALOG, true));
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.detailed_fragment, container, false);
}
}
This is my ActionBarActivity Class
This is the code for showing Dialog inside ActionBarActivity class.I think Please check your import statements
public class DetailedActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detailed_activity);
if (savedInstanceState == null) {
DetailedFragment fragment = DetailedFragment.newInstance(false);
getSupportFragmentManager().beginTransaction().add(R.id.root_layout_details, fragment, "Some_tag").commit();
}
}
}
I'm new to Android Preferences which I am using for a settings menu and I just had a few questions. I looked on the API site and couldn't find a way to add action to them. I have an Activity:
public class SettingsActivity extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
}
public static class MyPreferenceFragment extends PreferenceFragment
{
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
PreferenceManager.setDefaultValues(getActivity(), R.xml.preferences, false);
addPreferencesFromResource(R.xml.preferences);
}
}
}
which works fine, it displays my xml PreferenceScreen page which contains 4 Preference tags. My question is how do I add action when clicking on those preferences. For example I want a separate pop up window to be displayed where I can change a number value and for that to be saved each time I open the app. If someone could provide an example or something I would really appreciate it
I want a separate pop up window to be displayed where I can change a number value and for that to be saved
This is easy, you just have to make that Preference an EditTextPreference at your xml file like so:
<EditTextPreference
android:title="#string/title"
android:key="preferenceKey" />
You can customize it more: if you only want integers android:numeric="integer" , if you want to set the max length android:maxLength="3" and the default value android:defaultValue="10" . You don't have to do anything in the Java class
how do I add action when clicking on those preferences
If you want to add some more complicated action, use a Preference.OnPreferenceClickListener. You can use it like so:
Preference preference = // some preference
preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener(){
#Override
public boolean onPreferenceClick(Preference p){
//do something
return false;
}
});
You can find more at this question. Hope this helps
PS. If you want to customize the preference a lot (i.e. not only the action onClick, but also the layout etc), you should consider creating a custom Preference, as said at another answer.
It sounds like what you are trying to do would be appropriately handled by creating a custom Preference. The Android docs has a decent tutorial on this: http://developer.android.com/guide/topics/ui/settings.html#Custom
Based on your requirement, you can work through intents for your preference tags. below is my example code in Menu.java: and also you can follow the developer tutorial at : http://developer.android.com/guide/topics/ui/settings.html#Custom
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch(item.getItemId()){
case R.id.about:
/*Intent aboutIntent = new Intent(Menu.this, About.class);
startActivity(aboutIntent);*/
Intent aboutIntent = new Intent("com.example.myfirstapp.ABOUT");
startActivity(aboutIntent);
break;
case R.id.preference:
Intent prefsIntent = new Intent("com.example.myfirstapp.PREFS");
startActivity(prefsIntent);
break;
case R.id.exit:
finish();
break;
}
return false;
}
Code in About.java
public class About extends Activity {
TextView TV1;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.about);
TV1 = (TextView) findViewById (R.id.textView1);
}
}
When I run my application there is no menu button to go to the settings activity.
I have a settings activity which uses shared preferences. I call in the Main Activity like this:
private SharedPreferences settings;
private OnSharedPreferenceChangeListener listener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
settings = PreferenceManager.getDefaultSharedPreferences(this);
listener = new OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
}
};
settings.registerOnSharedPreferenceChangeListener(listener);
And this is my settings activity:
public class SettingsActivity extends PreferenceActivity {
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
}
And my settings.xml is in XML folder and its very simple at the moment. I just want to be able to open settings in my application. The XML is like this:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceCategory android:title="General settings" >
<EditTextPreference
android:key="pref_username"
android:title="User name" />
<CheckBoxPreference
android:key="pref_viewimages"
android:summary="Determines whether lists are shown with thumbnail photo"
android:title="View images"/>
</PreferenceCategory>
I've also added the settings activity to the Manifest file:
<activity
android:name=".SettingsActivity"></activity>
so far it eclipse doesn't show me any errors. But when I run my application there is no menu to go to the settings page! I was under the impression that when I create a settings activity, Android will automatically create a settings menu. But there is no menu button or anything. How can I fix this?
The menu and sharedpreferences are not directly linked. Shared preferences store values inside storage. Menu would be the graphical layout bringing you to PreferenceActivity that allow you to used shared preferences to store the settings.
You have to first inflate the menu like this in your activity :
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
where menu contains the menu details like these (res/menu/main.xml):
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<<item android:id="#+id/item1" android:title="Your setting name"></item>
</menu>
This would add "Your setting name" as an option when you click the menu button. Now to make the menu button do something use this (put it in your mainactivity) :
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle item selection
switch (item.getItemId())
{
case R.id.item1:
//Do something here like in my case launch intent to my new settings menu
Intent options1 = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(options1);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Now the menu button called "Your setting name" will launch your settings activity.
I don't think it's created by default. I had to do it myself. Anyway, check the menu file for your activity and check if this menu is used in your activity.
I have a menu that comes up for my PreferenceActivity. In my child preference screens, I lose that menu (doesn't pop up). How can I make my menu pop up for children too?
Thanks.
Example:
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
android:persistent="true">
<PreferenceCategory
android:title="some category"
android:persistent="true"
android:orderingFromXml="true">
<PreferenceScreen
android:title="some child screen"
android:summary="some child summary">
<PreferenceCategory
...
The first preference screen has the menu, but when you click on the child one, no menu. How can you add the menu?
I have better solution because Suriya's suffer from double showing of child's PreferenceScreen.
For child PreferenceScreen I use same PreferenceActivity. So at first for a child PreferenceScreen where we want to use option menu we set intent to our PreferenceActivity in onCreate method:
ourPreferenceScreen = (PreferenceScreen) findPreference("our_preference_screen");
if (ourPreferenceScreen != null) {
Intent intent = new Intent(this, PreferenceActivity.class);
intent.putExtra("ShowOurPreferenceScreen", true);
ourPreferenceScreen.setIntent(intent);
}
Then later in a same onCreate method we detect if our PreferenceActivity is started with extra flag. If so we switch to wanted PreferenceScreen:
if (getIntent().getBooleanExtra("ShowOurPreferenceScreen", false)) {
setPreferenceScreen(ourPreferenceScreen);
return;
}
And at the end we hande onCreateOptionMenu and other related option menu methods like this:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (getPreferenceScreen().equals(ourPreferenceScreen)) {
// your menu code
return true;
}
return super.onCreateOptionsMenu(menu);
}
I faced the similar issue. Here is what I did to overcome the issue.
In the preferenceActivity onCreate method,
final PreferenceScreen childPref = (PreferenceScreen) findPreference("childPrefId");
childPref .setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference)
{
Intent intent = new Intent(PreferenceActivity.this, YourSettings.class);
intent.setAction("ShowChildPref");
startActivity(intent);
return true;
}
});
Intent intent = getIntent();
if(intent.getAction() != null && intent.getAction().equals("ShowChildPref"))
{
setPreferenceScreen(childPref);
/*Set Flags here based on intent what kind of menu to create in OnPrepareMenu.*/
}
}
You have to add the code for the menu in each class that might want to bring up a menu using the menu button. Just because the other activity is in the background does not mean the menu will launch. It needs to be set in each class that wil be forground and need the menu available.