How to instantiate layout for custom preference, using android:layout attribute - android

I can set appropriate layout for preference through android:layout attribute. For an example
<Preference
android:key="friction"
android:title="#string/friction"
android:layout="#layout/friction_fragment"
android:shouldDisableView="true"
android:defaultValue="30"
android:enabled="true"
android:selectable="true"
android:summary="Bite friction">
</Preference>
where layout is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="#+id/textView1" android:layout_width="wrap_content" android:text="#string/friction" android:textAppearance="?android:attr/textAppearanceLarge" android:layout_height="wrap_content" android:layout_gravity="center_horizontal"></TextView>
<SeekBar android:layout_height="wrap_content" android:layout_width="fill_parent" android:id="#+id/sbFriction"></SeekBar>
<TextView android:text="#string/friction_little" android:id="#+id/txtSummary" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
<Button android:text="Button" android:id="#+id/btnFriction" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>
I can get views in OnCreate in PreferenceActivity
Preference fric = (Preference)this.findPreference("friction");
View v = fric.getView(null, null);
SeekBar sbFriction = (SeekBar)v.findViewById(R.id.sbFriction);
sbFriction.setOnSeekBarChangeListener(this);
Button btnFric = (Button) v.findViewById(R.id.btnFriction);
btnFric.setOnClickListener(m_onClick);
but these events listeners, that I have set, are not fired.
How I can catch these events, for example - click from button.
Edit.
No, It did not fire any exception.
Here is more detailed code
public class SettingsActivity extends PreferenceActivity implements OnPreferenceChangeListener, OnSeekBarChangeListener
{
private TextView m_txtSummary;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
ListPreference difficulty = (ListPreference)this.findPreference("difficulty");
difficulty.setSummary(difficulty.getEntry());
difficulty.setOnPreferenceChangeListener(this);
Preference fric = (Preference)this.findPreference("friction");
View v = fric.getView(null, null);
SeekBar sbFriction = (SeekBar)v.findViewById(R.id.sbFriction);
sbFriction.setOnSeekBarChangeListener(this);
Button btnFric = (Button) v.findViewById(R.id.btnFriction);
btnFric.setOnClickListener(m_onClick);
m_txtSummary = (TextView)v.findViewById(R.id.txtSummary);
fric.setSummary(fric.toString());
fric.setOnPreferenceChangeListener(this);
CheckBoxPreference music = (CheckBoxPreference)this.findPreference("music");
music.setOnPreferenceChangeListener(this);
}
private OnClickListener m_onClick = new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
v.getId();
}
};
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if(newValue instanceof Boolean)
return true;
preference.setSummary(newValue.toString());
return true;
}
#Override
public void onProgressChanged(SeekBar v, int nProgress, boolean arg2) {
// TODO Auto-generated method stub
m_txtSummary.append(" " + nProgress);
m_txtSummary.invalidate();
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
//notifyChanged();
}
}

I'm not sure you are able to use a custom layout in conjunction with a PreferenceActivity in the way that you describe above.
I believe you should either:
Use a PreferenceScreen via addPreferencesFromResource() and implement classes like CheckBoxPreference, DialogPreference, and MultiSelectListPreference for the SharedPreferences items. (example)
or
Create a custom Activity (not PreferenceActivity) with custom layout (using setContentView()), and manually hook into the SharedPreferences using PreferenceManager.getDefaultSharedPreferences() editing them in the event listeners (View.onClickListener(), etc) using SharedPreferences.Editor .
Hope that makes sense.

Actually I found for an another solution. You could still use the Preferenceability:
Simply add a Fragment which calls the Custom Layout and add it’s class.
However you'll get a warning in the Manifest: (which you can ignore or fix)
[res] (AndroidManifest.xml)
android:name=".SettingsActivity_CUSTOMLAYOUT1"
"YOURPACKAGE.SettingsActivity_CUSTOMLAYOUT1 is not public"
It's only called from your SettingsActivity so you can ignore it
or
if you want to call this Activity from outside just create an own class for it and name it SettingsActivity_CUSTOMLAYOUT1.java.
CODE:
[java] (SettingsActivity.java)
public class SettingsActivity extends AppCompatPreferenceActivity {
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);
} else if (preference instanceof RingtonePreference) {
if (TextUtils.isEmpty(stringValue)) {
preference.setSummary(R.string.pref_ringtone_silent);
} else {
Ringtone ringtone = RingtoneManager.getRingtone(
preference.getContext(), Uri.parse(stringValue));
if (ringtone == null) {
preference.setSummary(null);
} else {
String name = ringtone.getTitle(preference.getContext());
preference.setSummary(name);
}
}
} else {
preference.setSummary(stringValue);
}
return true;
}
};
private static boolean isXLargeTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
}
private static void bindPreferenceSummaryToValue(Preference preference) {
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupActionBar();
}
private void setupActionBar() {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onIsMultiPane() {
return isXLargeTablet(this);
}
#Override
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.pref_headers, target);
}
protected boolean isValidFragment(String fragmentName) {
return PreferenceFragment.class.getName().equals(fragmentName)
|| YOURFRAGMENT1.class.getName().equals(fragmentName)
|| YOURFRAGMENT2.class.getName().equals(fragmentName)
|| CUSTOMLAYOUT1.class.getName().equals(fragmentName)
//... Add Fragments
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class YOURFRAGMENT1 extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.YOURFRAGMENTXML1);
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);
}
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class YOURFRAGMENT2 extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_private_data);
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);
}
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class FRAGMENTFORCUSTOMLAYOUT1 extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startActivity(new Intent(getActivity(), SettingsActivity.class));
startActivity(new Intent(getActivity(), CUSTOMLAYOUT1.class));
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);
}
}
}
class SettingsActivity_CUSTOMLAYOUT1 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.CUSTOMLAYOUT1);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
[xml] (pref_headers.xml)
<preference-headers xmlns:android="http://schemas.android.com/apk/res/android">
<header
android:fragment="YOURPACKAGE.SettingsActivity$YOURFRAGMENT1"
android:icon="#drawable/YOURICON"
android:title="#string/TITLE"
android:summary="#string/SUBTITLE"/>
<header
android:fragment="YOURPACKAGE.SettingsActivity$YOURFRAGMENT2"
android:icon="#drawable/YOURICON"
android:title="#string/TITLE"
android:summary="#string/SUBTITLE"/>
<header
android:fragment="YOURPACKAGE.SettingsActivity$CUSTOMLAYOUT1"
android:icon="#drawable/YOURICON"
android:title="#string/TITLE"
android:summary="#string/SUBTITLE"/>
</preference-headers>
[layout] (CUSTOMLAYOUT1.xml)
<?xml version="1.0" encoding="utf-8"?>
<...your custom layout>
Dont forget to add in Manifest.
[res] (AndroidManifest.xml)
<?xml version="1.0" encoding="utf-8"?>
<manifest>
<application
//Add activity
<activity
android:name=".SettingsActivity_CUSTOMLAYOUT1"
android:parentActivityName=".SettingsActivity">
</activity>
</application>
</manifest>

Related

Shared Preferences not saved or recovered after setup in Settings Activity

I have done a basic Settings Activity. What I want, is when user selects a option from a list (in Settings), this will save the value, and a "flag".
With this flag I want to use it in the Main Activity, to force an api call.
The problem is that the values in Shared Preferences are not "working" properly...
Here is how I set up the settings activity:
public class SettingsActivity extends AppCompatPreferenceActivity {
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);
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.edit()
.putBoolean("reload_data", true).commit();
} else {
// For all other preferences, set the summary to the value's
// simple string representation.
preference.setSummary(stringValue);
}
return true;
}
};
private static boolean isXLargeTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
}
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();
addPreferencesFromResource(R.xml.pref_general);
}
/**
* 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);
}
/**
* This method stops fragment injection in malicious applications.
* Make sure to deny any unknown fragments here.
*/
protected boolean isValidFragment(String fragmentName) {
return SettingsFragment.class.getName().equals(fragmentName);
}
public static class SettingsFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
setHasOptionsMenu(true);
bindPreferenceSummaryToValue(findPreference(getString(R.string.languages_preferences_title)));
}
#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);
}
}
}
}
Notice that I put the shared preference to save the flag as:
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.edit()
.putBoolean("reload_data", true).commit();
And here is how I'm reading in MainActivity
#Override
protected void onResume() {
boolean reloadData = PreferenceManager
.getDefaultSharedPreferences(getBaseContext())
.getBoolean("reload_data", true);
if (reloadData && presenter != null) {
if (this.dailiesMap != null) {
this.dailiesMap.clear();
}
presenter.getDailiesAchievementModels();
PreferenceManager
.getDefaultSharedPreferences(getBaseContext())
.edit()
.putBoolean("reload_data", false).apply();
}
super.onResume();
}
When user it comes from Settings is suposed to be a true if user selects some option from the list. But this is not working. it comes to false.
First image is before change language(preference option)
Second image is after change language
As you can see , language change but not "my custom" key

EdittextPreference to set custom TextView

I have a TextView on my MainActivity which is a welcome text, it has a condition that if the user of my application has not set a username, it would only display "welcome" and if the user already sets their username, it would display the "welcome" text plus their username which has already assigned.
I am using the EdittextPreference & SharedPreference in this cause
the problem is, even the username has been set, it seems it is has not been set, because it doesn't trigger the if else condition i wrote between MainActivity & Settings, it still display the only "welcome" text.
I need some clue here..
my MainActivity.java >> https://paste.ubuntu.com/p/2n33ZzVkY4/
my Settings.java >> https://paste.ubuntu.com/p/JBWSqJfmG6/
you need to save there data in share preference and check if any data exist in share preference then display welcome + its user name both
You are saving the data on SharedPreferences.
You should use below code to get the data from sharedPreferences.
SharedPreferences sharedPreference = PreferenceManager.getDefaultSharedPreferences(this);
String userName = sharedPreference.getString("username", "");
Try the following complete example:
1) DemoActivity.class--------
public class DemoActivity extends AppCompatActivity{
private TextView tv;
private SharedPreferences demo_preferences;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo_activity);
demo_preferences = getSharedPreferences("demo_preference",
0);
tv = (TextView) findViewById(R.id.tv);
if(demo_preferences != null) {
String usn = demo_preferences.getString("username", "");
if (usn.isEmpty()) {
tv.setText("Welcome");
} else {
tv.setText("Welcome " + usn);
}
}else{
tv.setText("Welcome");
}
}
#Override
protected void onResume() {
super.onResume();
if(demo_preferences != null) {
String usn = demo_preferences.getString("username", "");
if (usn.isEmpty()) {
tv.setText("Welcome");
} else {
tv.setText("Welcome " + usn);
}
}else{
tv.setText("Welcome");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.demo_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.menu_settings:
Intent i = new Intent(DemoActivity.this , PrefDemoActivity.class);
startActivity(i);
break;
default:
throw new RuntimeException("unknown menu selection");
}
return true;
}
}
2) PrefDemoActivity:-------
public class PrefDemoActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentManager mFragmentManager = getFragmentManager();
FragmentTransaction mFragmentTransaction = mFragmentManager
.beginTransaction();
DemoEditPreferences mDemoPrefsFragment = new DemoEditPreferences();
mFragmentTransaction.replace(android.R.id.content, mDemoPrefsFragment);
mFragmentTransaction.commit();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
3) DemoEditPreferences:---------
public class DemoEditPreferences extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener{
private SharedPreferences demo_preferences;
private int preferencesToEdit;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
demo_preferences = getActivity().getSharedPreferences("demo_preference",
0);
preferencesToEdit = R.xml.demo_preferences;
String preferenceName = getResources().getString(R.string.pref_sensor_key);
PreferenceManager preferenceManager = getPreferenceManager();
preferenceManager.setSharedPreferencesName(preferenceName);
preferenceManager.setSharedPreferencesMode(0);
getActivity().setTitle("Demo Preferences");
addPreferencesFromResource(preferencesToEdit);
for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); i++) {
initSummary(getPreferenceScreen().getPreference(i));
}
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(findPreference(key) != null) {
if(findPreference(key).getKey().equals("username")) {
if(sharedPreferences.getString("username","").equals("")){
setString("username","");
}else{
setString("username",sharedPreferences.getString("username","----"));
}
}
updatePrefSummary(findPreference(key));
}
}
private void initSummary(Preference p) {
if (p instanceof PreferenceCategory) {
PreferenceCategory pCat = (PreferenceCategory) p;
for (int i = 0; i < pCat.getPreferenceCount(); i++) {
initSummary(pCat.getPreference(i));
}
} else {
updatePrefSummary(p);
}
}
private void updatePrefSummary(Preference p) {
if (p instanceof EditTextPreference) {
EditTextPreference editTextPref = (EditTextPreference) p;
p.setSummary(editTextPref.getText());
}
}
public void setString(String preferenceName, String value)
{
SharedPreferences.Editor editor = demo_preferences.edit();
editor.putString(preferenceName, value);
editor.apply();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
view.setBackgroundColor(getResources().getColor(android.R.color.white));
return view;
}
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onDestroy() {
super.onDestroy();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
}
4) demo_activity.xml:------
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Welcome"
android:id="#+id/tv"
android:gravity="center"
android:background="#android:color/holo_blue_light"/>
5) demo_menu.xml---------------
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/menu_settings"
android:title="Settings"
android:titleCondensed="Settings"
android:orderInCategory="1">
</item>
</menu>
6) demo_preferences:---------
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="Demo">
<EditTextPreference
android:key="username"
android:title="UserName"
android:defaultValue="----"
android:summary="----"
android:selectAllOnFocus="true"
android:singleLine="true">
</EditTextPreference>
</PreferenceCategory>
</PreferenceScreen>
7) Don't forget to add both activities to the manifest.

up button from preference fragment to return to preference headers

My app has preference headers on which you choose what fragment to start. After you are in some fragment I want that click on back button shows header again and if I press back again when headers are shown to return me to some other activity.
I overridded onOptionsItemSelected in Activity and in Fragment but it always calls action from activity because I am trying to bind fragment and activity to same action. Here is my code:
public class SettingsActivity extends AppCompatPreferenceActivity {
#Override
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.preference_headers, target);
}
#Override
protected boolean isValidFragment(String fragmentName) {
return SettingsFragment.class.getName().equals(fragmentName);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupActionBar();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
private void setupActionBar() {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
public static class SettingsFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
addPreferencesFromResource(R.xml.app_preferences);
}
#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 managed to solve this by removing onOptionsItemSelected method from activity and leave inside fragment. Now when I press up inside fragment it goes to SettingsActivity and when up is pressed inside activity it acts like onBackPressed(). Hope this helps somebody.

How to get toolbar in my PreferenceActivity

I've been trying to get a Toolbar to show up in my PreferenceActivity following the answer from Gabor using AppCompatPreferenceActivity shown here: Creating a Preference Screen with support (v21) Toolbar . However I can not get it to work. my code:
Settings.java:
public class Settings extends AppCompatPreferenceActivity{
#Override
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.preferences, target);
setContentView(R.layout.settings_page);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar bar = getSupportActionBar();
bar.setHomeButtonEnabled(true);
bar.setDisplayHomeAsUpEnabled(true);
bar.setDisplayShowTitleEnabled(true);
bar.setHomeAsUpIndicator(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
bar.setTitle("Test2");
}
#Override
protected boolean isValidFragment(String fragmentName) {
return MyPreferenceFragment.class.getName().equals(fragmentName);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
break;
}
return super.onOptionsItemSelected(item);
}
public static class MyPreferenceFragment extends PreferenceFragment
{
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
Preference removeMedalsButton = findPreference("removeMedals");
removeMedalsButton.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
Toast.makeText(getActivity(),"Medailles verwijderd",Toast.LENGTH_SHORT).show();
removeMedals(getActivity());
return true;
}
});
Preference removeWorkoutsButton = findPreference("removeWorkouts");
removeWorkoutsButton.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
Toast.makeText(getActivity(),"Workouts verwijderd",Toast.LENGTH_SHORT).show();
removeWorkouts();
return true;
}
});
Preference removeProfileButton = findPreference("removeProfile");
removeProfileButton.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
Toast.makeText(getActivity(),"Profiel verwijderd",Toast.LENGTH_SHORT).show();
removeProfile();
return true;
}
});
}
}
public static void removeMedals(Context context){
AchievementTracker.removeMedals(context);
}
public static void removeWorkouts(){
}
public static void removeProfile(){
}
}
settings_page.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="0dp"
android:orientation="vertical"
android:padding="0dp">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:theme="#style/ToolbarTheme"/>
<ListView
android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
preference.xml:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:title="#string/reminder_preference"
android:defaultValue="false"
android:summary="#string/reminder_preference_summary"
android:key="reminderPreference" />
<Preference android:title="#string/remove_medals"
android:key="removeMedals"
android:summary="#string/remove_medals_summary"/>
<Preference android:title="#string/remove_profile"
android:key="removeProfile"
android:summary="#string/remove_profile_summary"/>
<Preference android:title="#string/remove_workouts"
android:key="removeWorkouts"
android:summary="#string/remove_workouts_summary"/>
</PreferenceScreen>
The error i'm getting is:
XML document must start with <preference-headers> tag; foundPreferenceScreen at Binary XML file line #2
I think it's because i'm calling setContentView(R.Layout.settings_page) but that's how i'm supposed to do this according to Gabor's answer.

How can I retrieve shared preferences onCreate?

In the preferences I would like to change the preference view according the Unit type(Imprial or metric). On the create method I am checking what was the last value of the
measurement_unit preference, but always return metric on the app startup.
I also have a OnSharedPreferenceChangeListener where I am changing the view according the user entry, which is working. How can I get the saved preference when the onCreate is called?
public class PrefMainActivity extends PreferenceActivity{
String TAG="BlueGlucose";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle(R.string.action_settings);
this.init_view();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
SharedPreferences.OnSharedPreferenceChangeListener spChanged = new
SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {
PrefMainActivity.this.init_view();
}
// your stuff here
};
private void init_view(){
try
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String metric = getResources().getString(R.string.imperial);
if (prefs.getString("measurement_unit",metric) == metric)
getFragmentManager().beginTransaction().replace(android.R.id.content,
new PrefMainFragmentImperial()).commit();
else
getFragmentManager().beginTransaction().replace(android.R.id.content,
new PrefMainFragmentMetric()).commit();
prefs.registerOnSharedPreferenceChangeListener(spChanged);
}
catch(Exception ex)
{
}
}
if (prefs.getString("measurement_unit",metric) == metric)
String in java need to be compared by equals or equalsIgnoreCase

Categories

Resources