I am looking for a solution for my app to let the user select the font size via settings menu. Like I am able to do in other apps e.g. Jota+. Here are some screen shots for a better understanding (sorry - my Jota+ is a German version):
As of now I installed already a settingsActivity which is using a FragmentManager to call a PreferenceFragment using my pref_main.xml as resource.
Any idea how I can archive this?
My SettingsActivity:
package com.wbapps.wbshoppinglist;
/**
* Created by Andreas on 2/15/2018.
*/
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.view.MenuItem;
public class SettingsActivity extends AppCompatPreferenceActivity {
private static final String TAG = SettingsActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// load settings fragment
getFragmentManager().beginTransaction().replace(android.R.id.content, new MainPreferenceFragment()).commit();
}
public static class MainPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_main);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
private static void bindPreferenceSummaryToValue(Preference preference) {
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
/**
* A preference value change listener that updates the preference's summary
* to reflect its new value.
*/
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String stringValue = newValue.toString();
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list.
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
// Set the summary to reflect the new value.
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
}
else if (preference instanceof EditTextPreference) {
if (preference.getKey().equals("key_gallery_name")) {
// update the changed gallery name to summary filed
preference.setSummary(stringValue);
}
} else {
preference.setSummary(stringValue);
}
return true;
}
};
}
My AppCompatPreferenceActivity:
package com.wbapps.wbshoppinglist;
/**
* Created by Andreas on 2/15/2018.
*/
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.widget.Toolbar;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A {#link PreferenceActivity} which implements and proxies the necessary calls
* to be used with AppCompat.
*/
public abstract class AppCompatPreferenceActivity extends PreferenceActivity {
private AppCompatDelegate mDelegate;
#Override
protected void onCreate(Bundle savedInstanceState) {
getDelegate().installViewFactory();
getDelegate().onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
getDelegate().onPostCreate(savedInstanceState);
}
public ActionBar getSupportActionBar() {
return getDelegate().getSupportActionBar();
}
public void setSupportActionBar(#Nullable Toolbar toolbar) {
getDelegate().setSupportActionBar(toolbar);
}
#Override
public MenuInflater getMenuInflater() {
return getDelegate().getMenuInflater();
}
#Override
public void setContentView(#LayoutRes int layoutResID) {
getDelegate().setContentView(layoutResID);
}
#Override
public void setContentView(View view) {
getDelegate().setContentView(view);
}
#Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
getDelegate().setContentView(view, params);
}
#Override
public void addContentView(View view, ViewGroup.LayoutParams params) {
getDelegate().addContentView(view, params);
}
#Override
protected void onPostResume() {
super.onPostResume();
getDelegate().onPostResume();
}
#Override
protected void onTitleChanged(CharSequence title, int color) {
super.onTitleChanged(title, color);
getDelegate().setTitle(title);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getDelegate().onConfigurationChanged(newConfig);
}
#Override
protected void onStop() {
super.onStop();
getDelegate().onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
getDelegate().onDestroy();
}
public void invalidateOptionsMenu() {
getDelegate().invalidateOptionsMenu();
}
private AppCompatDelegate getDelegate() {
if (mDelegate == null) {
mDelegate = AppCompatDelegate.create(this, null);
}
return mDelegate;
}
}
My pref_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="#string/pref_header_font_setting">
<Preference
android:summary="#string/pref_font_setting"/>
</PreferenceCategory>
<PreferenceCategory android:title="#string/pref_header_about">
<Preference
android:selectable="false"
android:summary="#string/summary_about" />
<Preference
android:summary="#string/app_version"
android:title="#string/title_version" />
</PreferenceCategory>
</PreferenceScreen>
Here you can see the project structure:
Many thanks
Andreas
Related
I have a on/off switch called audio_switch. In my MainActivity file I want to look if the switch is on, if so, it should set a variable audio = 1. This piece of code mentioned can be found at the bottom of my MainActivity. On the very top after you can see I added a line to find my audio file. A few lines later I used an if(audio == 1) statement to check if the switch is on, so it will play the audio. This however does not work, it does however when I change the statement to audio == audio
package com.joeridukker.main;
import android.animation.ArgbEvaluator;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.support.constraint.ConstraintLayout;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
public static int audio;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer MansNotHot = MediaPlayer.create(this, R.raw.mans_not_hot);
if(audio == 1){
MansNotHot.start();
}
int secondsDelayed = 1;
Handler start = new Handler();
start.postDelayed(new Runnable() {
public void run() {
Animation wait = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.wait);
ConstraintLayout Entire = (ConstraintLayout) findViewById(R.id.Entire);
ImageView Logo = (ImageView) findViewById(R.id.Logo);
TextView Welcome = (TextView) findViewById(R.id.Welcome);
Welcome.startAnimation(wait);
Entire.startAnimation(wait);
Logo.startAnimation(wait);
// Actions to do after 10 seconds
}
}, 0);
Handler animation = new Handler();
animation.postDelayed(new Runnable() {
public void run() {
Animation slide_up = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.fade_and_slide_upwards);
Animation slide_down = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.fade_and_slide_downwards);
TextView Welcome = (TextView) findViewById(R.id.Welcome);
ImageView Logo = (ImageView) findViewById(R.id.Logo);
Logo.startAnimation(slide_down);
Welcome.startAnimation(slide_up);
// Actions to do after 10 seconds
}
}, 500);
Handler entire_animation = new Handler();
entire_animation.postDelayed(new Runnable() {
public void run() {
Animation fade_in = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.fade_in);
ConstraintLayout Entire = (ConstraintLayout) findViewById(R.id.Entire);
TextView Welcome = (TextView) findViewById(R.id.Welcome);
Entire.startAnimation(fade_in);
ObjectAnimator.ofObject(
Welcome,
"textColor",
new ArgbEvaluator(),
Color.argb(140,0,0,0),
Color.WHITE
).setDuration(500)
.start();
}
}, 500);
new Handler().postDelayed(new Runnable() {
public void run() {
Handler splash = new Handler();
int a = 1;
Intent Intent = new Intent(MainActivity.this, Differentiate.class);
Intent.putExtra("HEADER", a);
startActivity(Intent);
overridePendingTransition(R.anim.fade_in_switch_fast,R.anim.fade_out_switch_fast);
finish();
}
}, secondsDelayed * 2500);
}
public static class SettingsActivity extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.pref_general);
//Check the current value in preference.
SharedPreferences switchPrefStatus = PreferenceManager.getDefaultSharedPreferences(getActivity());
boolean switchPrefValue = switchPrefStatus.getBoolean("audio_switch", false);
Toast.makeText(getActivity(), "Current value: " + switchPrefValue, Toast.LENGTH_SHORT).show();
Preference switchPref = (Preference) findPreference("audio_switch");
switchPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object o) {
boolean isOn = (boolean) o;
//Do what you want with the value!:)
if (isOn) {
audio = 1;
}else{
audio = 0;
}
return true;
}
});
}
}
}
My SettingsActivity
package com.joeridukker.main;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.preference.RingtonePreference;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.view.MenuItem;
import java.util.List;
/**
* A {#link PreferenceActivity} that presents a set of application settings. On
* handset devices, settings are presented as a single list. On tablets,
* settings are split by category, with category headers shown to the left of
* the list of settings.
* <p>
* See <a href="http://developer.android.com/design/patterns/settings.html">
* Android Design: Settings</a> for design guidelines and the <a
* href="http://developer.android.com/guide/topics/ui/settings.html">Settings
* API Guide</a> for more information on developing a Settings UI.
*/
public class SettingsActivity extends AppCompatPreferenceActivity {
/**
* A preference value change listener that updates the preference's summary
* to reflect its new value.
*/
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list.
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
// Set the summary to reflect the new value.
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
} else if (preference instanceof RingtonePreference) {
// For ringtone preferences, look up the correct display value
// using RingtoneManager.
if (TextUtils.isEmpty(stringValue)) {
// Empty values correspond to 'silent' (no ringtone).
preference.setSummary(R.string.pref_ringtone_silent);
} else {
Ringtone ringtone = RingtoneManager.getRingtone(
preference.getContext(), Uri.parse(stringValue));
if (ringtone == null) {
// Clear the summary if there was a lookup error.
preference.setSummary(null);
} else {
// Set the summary to reflect the new ringtone display
// name.
String name = ringtone.getTitle(preference.getContext());
preference.setSummary(name);
}
}
} else {
// For all other preferences, set the summary to the value's
// simple string representation.
preference.setSummary(stringValue);
}
return true;
}
};
/**
* Helper method to determine if the device has an extra-large screen. For
* example, 10" tablets are extra-large.
*/
private static boolean isXLargeTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
}
/**
* Binds a preference's summary to its value. More specifically, when the
* preference's value is changed, its summary (line of text below the
* preference title) is updated to reflect the value. The summary is also
* immediately updated upon calling this method. The exact display format is
* dependent on the type of preference.
*
* #see #sBindPreferenceSummaryToValueListener
*/
private static void bindPreferenceSummaryToValue(Preference preference) {
// Set the listener to watch for value changes.
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
// Trigger the listener immediately with the preference's
// current value.
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupActionBar();
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
private void setupActionBar() {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
// Show the Up button in the action bar.
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
if (!super.onMenuItemSelected(featureId, item)) {
NavUtils.navigateUpFromSameTask(this);
}
return true;
}
return super.onMenuItemSelected(featureId, item);
}
/**
* {#inheritDoc}
*/
#Override
public boolean onIsMultiPane() {
return isXLargeTablet(this);
}
/**
* {#inheritDoc}
*/
#Override
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.pref_headers, target);
}
/**
* This method stops fragment injection in malicious applications.
* Make sure to deny any unknown fragments here.
*/
protected boolean isValidFragment(String fragmentName) {
return PreferenceFragment.class.getName().equals(fragmentName)
|| GeneralPreferenceFragment.class.getName().equals(fragmentName)
|| DataSyncPreferenceFragment.class.getName().equals(fragmentName)
|| NotificationPreferenceFragment.class.getName().equals(fragmentName);
}
/**
* This fragment shows general preferences only. It is used when the
* activity is showing a two-pane settings UI.
*/
static int audio;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class GeneralPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
setHasOptionsMenu(true);
Preference switchPref = (Preference) findPreference("audio_switch");
switchPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object o) {
boolean isOn = (boolean) o;
if (isOn) {
audio = 1;
}else{
audio = 0;
}
return true;
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
/**
* This fragment shows notification preferences only. It is used when the
* activity is showing a two-pane settings UI.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class NotificationPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_notification);
setHasOptionsMenu(true);
// Bind the summaries of EditText/List/Dialog/Ringtone preferences
// to their values. When their values change, their summaries are
// updated to reflect the new value, per the Android Design
// guidelines.
bindPreferenceSummaryToValue(findPreference("notifications_new_message_ringtone"));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
/**
* This fragment shows data and sync preferences only. It is used when the
* activity is showing a two-pane settings UI.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class DataSyncPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_data_sync);
setHasOptionsMenu(true);
// Bind the summaries of EditText/List/Dialog/Ringtone preferences
// to their values. When their values change, their summaries are
// updated to reflect the new value, per the Android Design
// guidelines.
bindPreferenceSummaryToValue(findPreference("sync_frequency"));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
}
I use the official SettingsActivity as my activity's templete,and my preferenceactivity have two static class "preferencefragment1" and "preferencefragment2".
While the App click the headers of the preferenceactivity, it switch to the specified preferencefragment.Then I call the finished() method in the onkeydown() method with the KEYCODE_BACK event.It will back to the headers view.
However,what I want is it back to the mainactivity from preferencefragment view,make the whole PreferenceActivity to finish instead of just the preferencefragment1 view.
Because I want to use the the preferenceActivity to set the parameters of a bluetooth comunication device,and after parameters finished setting, it can immediately send the parameteres to the deivce in the onActivityResult() method.
But now, I must click the BACK button twice to back to the mainactivity.Is that a possible to skip the header view to show or jump into the preferencefragment view directly?
program flow
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.app.ActionBar;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.preference.SwitchPreference;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import java.util.List;
public class SettingsActivity extends PreferenceActivity {
private static List<Header> headers;
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
}
if (preference instanceof EditTextPreference) {
EditTextPreference editTextPreference = (EditTextPreference) preference;
editTextPreference.setSummary(stringValue);
}
if (preference instanceof SwitchPreference) {
SwitchPreference switchPreference = (SwitchPreference) preference;
switchPreference.setSummary(stringValue);
}
return true;
}
};
private static boolean isXLargeTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Confirm to update system paras?");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
setResult(RESULT_OK);
finish();
}
});
builder.setNegativeButton("CANCELED", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.show();
}
return super.onKeyDown(keyCode, event);
}
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data)
{
System.out.print(resultCode);
}
private static void bindPreferenceSummaryToValue(Preference preference) {
// Set the listener to watch for value changes.
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
// Trigger the listener immediately with the preference's
// current value.
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// addPreferencesFromResource(R.xml.pref_system);
setupActionBar();
}
private void setupActionBar() {
ActionBar actionBar = getActionBar();
if (actionBar != null) {
// Show the Up button in the action bar.
// actionBar.setDisplayHomeAsUpEnabled(true);
}
}
/**
* {#inheritDoc}
*/
#Override
public boolean onIsMultiPane() {
return isXLargeTablet(this);
}
/**
* {#inheritDoc}
*/
#Override
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.pref_headers, target);
headers=target;
}
/**
* This method stops fragment injection in malicious applications.
* Make sure to deny any unknown fragments here.
*/
protected boolean isValidFragment(String fragmentName) {
return PreferenceFragment.class.getName().equals(fragmentName)
|| SystemPreferenceFragment.class.getName().equals(fragmentName);
}
/**
* This fragment shows general preferences only. It is used when the
* activity is showing a two-pane settings UI.
*/
public static class SystemPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_system);
setHasOptionsMenu(true);
bindPreferenceSummaryToValue(findPreference("pref_key_ip"));
bindPreferenceSummaryToValue(findPreference("pref_key_port"));
bindPreferenceSummaryToValue(findPreference("pref_key_output1_level"));
bindPreferenceSummaryToValue(findPreference("pref_key_output2_level"));
bindPreferenceSummaryToValue(findPreference("pref_key_output3_level"));
bindPreferenceSummaryToValue(findPreference("pref_key_noportrait"));
bindPreferenceSummaryToValue(findPreference("pref_key_closeeye"));
bindPreferenceSummaryToValue(findPreference("pref_key_yawn"));
bindPreferenceSummaryToValue(findPreference("pref_key_distract"));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
/*
#Override
public void onStop()
{
super.onStop();
AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
builder.setTitle("Confirm to update system paras?");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
SystemPreferenceFragment.this.getActivity().setResult(RESULT_OK);
}
});
builder.setNegativeButton("CANCELED", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
SystemPreferenceFragment.this.getActivity().setResult(RESULT_CANCELED);
}
});
builder.show();
this.getActivity().finish();
}*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class RealtimePreferenceFragment extends PreferenceFragment {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_realtime);
setHasOptionsMenu(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
}
Use getActivity().finish(); to finish the activity
or
expose a method using interface from fragment to activity to notify back is being pressed
Problem solved!!
step 1:In the MainActivity, add flag "FLAG_ACTIVITY_NO_HISTORY" to the Intent, then start the SettingsActivity.
step 2: Override the onBuildStartFragmentIntent() method of SettingsActivity(PreferenceActivity) for adding flag FLAG_ACTIVITY_FORWARD_RESULT,so that the activityresult can return to the MainActivity.
Like below: #Override
public Intent onBuildStartFragmentIntent (String fragmentName,
Bundle args,
int titleRes,
int shortTitleRes)
{
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClass(this, getClass());
intent.putExtra(EXTRA_SHOW_FRAGMENT, fragmentName);
intent.putExtra(EXTRA_SHOW_FRAGMENT_ARGUMENTS, args);
intent.putExtra(EXTRA_SHOW_FRAGMENT_TITLE, titleRes);
intent.putExtra(EXTRA_SHOW_FRAGMENT_SHORT_TITLE, shortTitleRes);
intent.putExtra(EXTRA_NO_HEADERS, true);
intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);//the new statement
return intent;
}
I work with preference xml file as options menu and i use it in my java class like bellwo
but the compiler says its deprecated and add a black line on addpreffrencefromresource(R.xml.mypreff). what is the new way of coding for it? thank you for helping.
package com.bestdiet;
import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.view.MenuItem;
public class prefs extends PreferenceActivity{
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.mypref);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
// return super.onOptionsItemSelected(item);
switch(item.getItemId())
{
case R.id.exit:
finish();
break;
case R.id.help:
break;
case R.id.options:
break;
}
return false;
}
xml file:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<CheckBoxPreference
android:title="پخش صدا"
android:defaultValue="true"
android:key="checkbox1"
/>
<CheckBoxPreference
android:title="پخش موسیقی"
android:defaultValue="true"
android:key="checkbox2"/>
</PreferenceScreen>
There is something notable: I just used the same xml preference layout...
But nobody tells you not to use two different files (say prefs_old.xml and prefs_new.xml), to add some of the new features to the (new) PreferenceFragment version of your PreferenceScreen.
This is my PreferenceActivity. It simply checks the build version to see which version of the preferences must be prepared:
package com.example.android.scheduler2;
/* ---------------------------------- Imports ------------------------------- */
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.widget.ListView;
public final class ACT_Prefs
extends PreferenceActivity
implements OnSharedPreferenceChangeListener
{
/* ------------------------------ Objects ------------------------------- */
private Context ctx = null;
/* ----------------------------- Overrides ------------------------------ */
#Override
public final void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
ctx = getApplicationContext();
if (Build.VERSION.SDK_INT < 11)
{
createPreference_Activity();
}
else
{
createPreference_Fragment();
}
}
#Override
protected void onPause()
{
// Unregister OnSharedPreferenceChangeListener
PreferenceManager.getDefaultSharedPreferences(ctx).
unregisterOnSharedPreferenceChangeListener(this);
// Call base method
super.onPause();
}
#Override
protected void onResume()
{
// Register OnSharedPreferenceChangeListener
PreferenceManager.getDefaultSharedPreferences(ctx).
registerOnSharedPreferenceChangeListener(this);
// Fire base method
super.onResume();
}
#Override
public void onSharedPreferenceChanged
(final SharedPreferences sharedPreferences, final String key)
{
// ... Do whatever you need to do here ...
System.out.println(key + " changed!!");
}
/* ------------------------------ Methods ------------------------------- */
//#SuppressWarnings("deprecation")
private final void createPreference_Activity()
{
addPreferencesFromResource(R.xml.prefs);
}
#SuppressLint("NewApi")
private final void createPreference_Fragment()
{
getFragmentManager().beginTransaction().replace
(android.R.id.content, new FRG_Prefs()).commit();
getFragmentManager().executePendingTransactions();
}
}
This is FRG_Prefs (the PreferenceFragment)
package com.example.android.scheduler2;
/* ---------------------------------- Imports ------------------------------- */
import android.annotation.SuppressLint;
import android.graphics.PixelFormat;
import android.preference.PreferenceFragment;
import android.view.View;
import android.widget.ListView;
#SuppressLint("NewApi")
public final class FRG_Prefs
extends PreferenceFragment
{
/* ----------------------------- Overrides ------------------------------ */
#Override
public final void onResume()
{
super.onResume();
addPreferencesFromResource(R.xml.prefs);
}
}
The issue I am having is that I have created a simple count down timer, using AsyncTasks and using the SetRetainInstance(true) to ensure that even with orientation change the counter updates on the ui.
The issue is that I have an editText that gives me the values for the timer and then should pass them on to the Task to count Down. I must be missing something somewhere because, I cannot seem to get the new value.
This is the code that I am using as the Fragment:
package com.example.app;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.util.Log;
public class TaskFragment extends Fragment {
private static final String TAG = TaskFragment.class.getSimpleName();
String i;
int counter;
Bundle bundle;
static interface TaskCallbacks {
public void onPreExecute();
public void onProgressUpdate(int timer);
public void onCancelled();
public void onPostExecute();
}
private TaskCallbacks mCallbacks;
private DummyTask mTask;
private boolean mRunning;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (!(activity instanceof TaskCallbacks)) {
throw new IllegalStateException("Activity must implement the TaskCallbacks interface.");
}
mCallbacks = (TaskCallbacks) activity;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
bundle=getArguments();
i = bundle.getString("SecValue");
Log.i("VertygoEclypse - TaskFragment-onCreate", i);
counter=Integer.parseInt(i);
}
#Override
public void onDestroy() {
super.onDestroy();
cancel();
}
public void start() {
if (!mRunning) {
bundle=getArguments();
i=bundle.getString("SecValue");
mTask = new DummyTask();
Log.i("VertygoEclypse - TaskFragment - start", i);
mTask.execute();
mRunning = true;
} else{
mTask.cancel(true);
}
}
public void cancel() {
if (mRunning) {
mTask.cancel(true);
mTask = null;
mRunning = false;
}
}
public boolean isRunning() {
return mRunning;
}
private class DummyTask extends AsyncTask<Void, Integer, Void> {
#Override
protected void onPreExecute() {
mCallbacks.onPreExecute();
mRunning = true;
counter=Integer.parseInt(i);
Log.i("Vertygo Eclypse - AsyncTask - onPreExecute", i);
}
#Override
protected Void doInBackground(Void... ignore) {
do {
publishProgress(counter);
SystemClock.sleep(1000);
counter=counter-1;
if(isCancelled()){
mTask.cancel(true);
break;
}
} while (counter>0);
return null;
}
#Override
protected void onProgressUpdate(Integer... timer) {
mCallbacks.onProgressUpdate(timer[0]);
}
#Override
protected void onCancelled() {
mCallbacks.onCancelled();
mRunning = false;
}
#Override
protected void onPostExecute(Void ignore) {
mCallbacks.onPostExecute();
mRunning = false;
}
}
}
That being said I have Log.i set up at a number of spots the onCreate, the start, the pre-execute and the post-execute.
The following excerpt from the logcat shows that some of the values show the entered text, but the start and preexecute are holding the old values:
01-17 17:37:12.383 10261-10261/com.example.app I/VertygoEclypse - replaceFrag﹕ 35
01-17 17:37:12.383 10261-10261/com.example.app I/VertygoEclypse - replaceFrag﹕ 35
01-17 17:37:12.383 10261-10261/com.example.app I/Vertygo Eclypse - MainActivity - replaceFrag﹕ 35
01-17 17:37:12.403 10261-10261/com.example.app I/VertygoEclypse - TaskFragment-onCreate﹕ 35
01-17 17:37:17.247 10261-10261/com.example.app I/VertygoEclypse - TaskFragment - start﹕ 15
01-17 17:37:17.259 10261-10261/com.example.app I/Vertygo Eclypse - AsyncTask - onPreExecute﹕ 15
I am also using Bundle to transfer the text from an EditText to the fragment and using getString() to get the value based on a key.
Below is the MainActivity so far.
package com.example.app;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import java.util.concurrent.TimeUnit;
public class MainActivity extends FragmentActivity implements TaskFragment.TaskCallbacks {
private static final String TAG = MainActivity.class.getSimpleName();
private static final String KEY_CURRENT_PROGRESS = "current_progress";
private static final String KEY_PERCENT_PROGRESS = "percent_progress";
private static final String TIME_COUNT = "time_count";
private TaskFragment mTaskFragment;
private ProgressBar mProgressBar;
private TextView mPercent, tv1;
private Button mButton;
private EditText secentered;
public String sample;
Bundle bundl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView) findViewById(R.id.textView1);
secentered = (EditText) findViewById(R.id.valueentered);
mButton = (Button) findViewById(R.id.task_button);
initialfrag();
mButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mTaskFragment.isRunning()) {
mButton.setText("Start");
mTaskFragment.cancel();
replaceFrag();
} else {
mButton.setText("Cancel");
mTaskFragment.start();
}
}
});
if (savedInstanceState != null) {
tv1.setText(savedInstanceState.getString(TIME_COUNT));
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(TIME_COUNT, tv1.getText().toString());
}
#Override
public void onPreExecute() {
mButton.setText(getString(R.string.cancel));
Toast.makeText(this, R.string.task_started_msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onProgressUpdate(int timer) {
long timelong = timer*1000;
String tval = getDurationBreakdown(timelong);
tv1.setText(tval);
}
#Override
public void onCancelled() {
mButton.setText(getString(R.string.start));
tv1.setText("0 seconds");
mTaskFragment.cancel();
replaceFrag();
Toast.makeText(this, R.string.task_cancelled_msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onPostExecute() {
mButton.setText(getString(R.string.start));
tv1.setText("Completed");
mTaskFragment.cancel();
replaceFrag();
Toast.makeText(this, R.string.task_complete_msg, Toast.LENGTH_SHORT).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_trigger_config_change:
recreate();
return true;
}
return super.onOptionsItemSelected(item);
}
public static String getDurationBreakdown(long secondstobreak) {
if(secondstobreak < 0)
{
throw new IllegalArgumentException("Duration must be greater than zero!");
}
long hours = TimeUnit.MILLISECONDS.toHours(secondstobreak);
secondstobreak-=TimeUnit.HOURS.toMillis(hours);
long minutes = TimeUnit.MILLISECONDS.toMinutes(secondstobreak);
secondstobreak-=TimeUnit.MINUTES.toMillis(minutes);
long seconds = TimeUnit.MILLISECONDS.toSeconds(secondstobreak);
secondstobreak-=TimeUnit.SECONDS.toMillis(seconds);
StringBuilder sb = new StringBuilder(64);
if(hours<10){
sb.append("0"+hours);
}else {
sb.append(hours);
}
sb.append(" : ");
if(minutes<10){
sb.append("0"+minutes);
}else{
sb.append(minutes);
}
sb.append(" : ");
if(seconds<10){
sb.append("0"+seconds);
} else {
sb.append(seconds);
}
sb.append(" remaining");
return (sb.toString());
}
public void replaceFrag(){
Bundle bundle = new Bundle();
String tester2 = secentered.getText().toString();
Log.i("VertygoEclypse - replaceFrag", tester2);
if(tester2.matches("")){
bundle.putString("SecValue", "15");
} else {
Log.i("VertygoEclypse - replaceFrag", tester2);
bundle.putString("SecValue", tester2);
}
FragmentTransaction rfm = getSupportFragmentManager().beginTransaction();
rfm.remove(mTaskFragment);
rfm.detach(mTaskFragment);
TaskFragment mTaskFragment = new TaskFragment();
Log.i("Vertygo Eclypse - MainActivity - replaceFrag", tester2);
mTaskFragment.setArguments(bundle);
rfm.add(mTaskFragment, "task").commit();
}
public void initialfrag(){
bundl = new Bundle();
String tester = secentered.getText().toString();
Log.i("VertygoEclypse - initialFrag", tester);
if(tester.matches("")){
bundl.putString("SecValue", "15");
} else{
Log.i("VertygoEclypse - initialFrag", tester);
bundl.putString("SecValue", tester);
}
FragmentManager fm = getSupportFragmentManager();
mTaskFragment = (TaskFragment) fm.findFragmentByTag("task");
if (mTaskFragment == null) {
mTaskFragment = new TaskFragment();
mTaskFragment.setArguments(bundl);
fm.beginTransaction().add(mTaskFragment, "task").commit();
}
}
}
I know that the value is being passed to the fragment, however I am not certain if the AsyncTask or the Fragment is being replaced or refreshed. What I would like Ideally is to have the AsyncTask killed and a new one created using the new value from the Bundle.
Any help would be greatly appreciated.
Ok all it seems that I have stumbled upon the answer. the issue was th int counter, validcounter; it seems that without the static in front of it, the variable creates it's own instance of it. so with the following static int counter, validcounter; the issue is resolved.
thanks for the sounding board.
regards
cchinchoy
Before I start, yes I have read countless related questions. I still can't seem to track down the issue.
I have a SherlockFragmentActivity:
package com.kicklighterdesignstudio.floridaday;
import android.os.Bundle;
import android.support.v4.app.Fragment;
public class FragmentActivity extends BaseActivity {
public static final String TAG = "FragmentActivity";
public static final int SCHEDULE_FRAGMENT = 0;
public static final int MAP_FRAGMENT = 1;
public static final int FOOD_FRAGMENT = 2;
public static final int TWITTER_FRAGMENT = 3;
public static final int HASHTAG_FRAGMENT = 4;
private Fragment mContent;
public FragmentActivity() {
super(R.string.main_activity_title);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_frame);
switchContent(SCHEDULE_FRAGMENT);
setBehindContentView(R.layout.menu_frame);
}
public void switchContent(int id) {
getFragment(id);
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, mContent)
.commit();
getSlidingMenu().showContent();
}
private void getFragment(int id) {
switch (id) {
case 0:
mContent = new ScheduleFragment();
break;
case 1:
mContent = new FoodFragment();
break;
case 2:
mContent = new MapFragment();
break;
case 3:
mContent = new TwitterFragment();
break;
case 4:
mContent = new HashtagFragment();
break;
}
}
}
It extends BaseActivity:
package com.kicklighterdesignstudio.floridaday;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import com.actionbarsherlock.view.MenuItem;
import com.slidingmenu.lib.SlidingMenu;
import com.slidingmenu.lib.app.SlidingFragmentActivity;
public class BaseActivity extends SlidingFragmentActivity {
// private int mTitleRes;
protected ListFragment mFrag;
public BaseActivity(int titleRes) {
// mTitleRes = titleRes;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setTitle(mTitleRes);
setTitle("");
// set the Behind View
setBehindContentView(R.layout.menu_frame);
if (savedInstanceState == null) {
FragmentTransaction t = this.getSupportFragmentManager().beginTransaction();
mFrag = new MenuFragment();
t.replace(R.id.menu_frame, mFrag);
t.commit();
} else {
mFrag = (ListFragment) this.getSupportFragmentManager().findFragmentById(
R.id.menu_frame);
}
// customize the SlidingMenu
SlidingMenu sm = getSlidingMenu();
sm.setShadowWidthRes(R.dimen.shadow_width);
sm.setShadowDrawable(R.drawable.shadow);
sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);
sm.setFadeDegree(0.35f);
sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
sm.setBehindScrollScale(0.0f);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
toggle();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Right now, I'm only concerned with ScheduleFragment:
package com.kicklighterdesignstudio.floridaday;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.actionbarsherlock.app.SherlockFragment;
public class ScheduleFragment extends SherlockFragment implements OnItemClickListener {
public static final String TAG = "ScheduleFragment";
private ArrayList<ScheduleItem> schedule;
private FloridaDayApplication app;
public ScheduleFragment() {
// setRetainInstance(true);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
app = (FloridaDayApplication) activity.getApplication();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.schedule_fragment, container, false);
}
#Override
public void onStart() {
super.onStart();
getSherlockActivity().getSupportActionBar().setTitle(R.string.schedule_fragment);
schedule = app.getSchedule();
ListView scheduleListView = (ListView) getActivity().findViewById(R.id.schedule_list);
ScheduleItemAdapter adapter = new ScheduleItemAdapter(getActivity(), schedule);
scheduleListView.setAdapter(adapter);
scheduleListView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> a, View v, int id, long position) {
Fragment newFragment = new ScheduleItemFragment(id);
FragmentTransaction transaction = getSherlockActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.content_frame, newFragment).addToBackStack(null).commit();
}
}
ScheduleFragment displays a list of schedule items. When clicked, a new fragment is displayed (ScheduleItemFragment) to show details of the item and a map to its location:
package com.kicklighterdesignstudio.floridaday;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.model.MarkerOptions;
#SuppressLint("ValidFragment")
public class ScheduleItemFragment extends SherlockFragment {
public static final String TAG = "ScheduleItemFragment";
private int scheduleItemId;
private FloridaDayApplication app;
private ScheduleItem scheduleItem;
private MapView mapView;
private GoogleMap map;
public ScheduleItemFragment(int id) {
scheduleItemId = id;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
app = (FloridaDayApplication) activity.getApplication();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.schedule_item_fragment, container, false);
setHasOptionsMenu(true);
// Initialize MapView
mapView = (MapView) v.findViewById(R.id.map_view);
mapView.onCreate(savedInstanceState);
return v;
}
#Override
public void onStart() {
super.onStart();
scheduleItem = app.getSchedule().get(scheduleItemId);
getSherlockActivity().getSupportActionBar().setTitle(scheduleItem.getTitle());
// Map Stuff
map = mapView.getMap();
if (map != null) {
map.getUiSettings();
map.setMyLocationEnabled(true);
try {
MapsInitializer.initialize(getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
// Add marker to the map
MarkerOptions options = new MarkerOptions().position(scheduleItem.getLocation().getPosition()).title(
scheduleItem.getLocation().getTitle());
map.addMarker(options);
// Adjust Camera Programmatically
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(
scheduleItem.getLocation().getPosition(), 14);
map.animateCamera(cameraUpdate);
} else {
Log.i(TAG, "Map is null");
}
// Other Views
TextView title = (TextView) getSherlockActivity().findViewById(R.id.title);
TextView time = (TextView) getSherlockActivity().findViewById(R.id.time);
TextView description = (TextView) getSherlockActivity().findViewById(R.id.description);
title.setText(scheduleItem.getTitle());
time.setText(scheduleItem.getDateTimeString());
description.setText(scheduleItem.getDescription());
}
// TODO: Make this work
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
getFragmentManager().popBackStack();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public void onDestroy() {
mapView.onDestroy();
super.onDestroy();
}
#Override
public void onLowMemory() {
mapView.onLowMemory();
super.onLowMemory();
}
#Override
public void onPause() {
mapView.onPause();
super.onPause();
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onSaveInstanceState(Bundle outState) {
mapView.onSaveInstanceState(outState);
super.onSaveInstanceState(outState);
}
}
Thanks to BaseActivity, the icon in my ActionBar is clickable. It toggles the Sliding Menu. When viewing a ScheduleItemFragment, I would like the icon to return to the previous item in the backstack (which you can see I'm trying to do.) No matter what I try, the icon always toggles the Sliding Menu. Any thoughts on how to guarantee my Fragment gains control of the ActionBar menu clicks?
you need to call setHasOptionsMenu(true); in onCreate, not onCreateView
also I'm interested what happens when you debug, does onOptionsItemSelected still get called?
edit: add the following to your fragment
#Override
public void onCreate(Bundle savedInstanceState) {
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
edit1:
there may be a better way to do this but I'm not exactly sure how your fragments are setup out, create a public field in baseActivity public bool isItemFragmentOnTop
now onOptionsItemSelected in the case of the home button getting press do this
if (isItemFragmentOnTop){
getFragmentManager().popBackStack();
isItemFragmentOnTop = false;
} else {
toggle();
}
return true;
then in your fragment you can call ((BaseActivity)getActivity).isItemFragmentOnTop = true; to make the home button pop the back stack, you would want to do this when you display your fragment onItemClick in your list view.