How can I retrieve shared preferences onCreate? - android

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

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

Why does using Locale in Fragment result in lots of bugs?

I have two activity namely MainActivity.java and Settings.java and others are fragments, MainActivity is the fragment_container, every fragment is attached here. Settings activity has the settings of changing language. MainActivity contains three buttons and if I click on the button next fragment in a same container displays listview.
If I change the language then if I come back to MainActivity from settings activity and then click on button the listview is still displaying English language. If I pressed back and again click on button then finally language are changed. Although the language aren't change in menu(onOptionsCreateMenu). I saved those settings in the sharedPreferences.
Now, after I exit my app and again come back then again same thing, if I click the button for the first time the language are in English if I come back to fragment and again click on button it changes language. What might be I missing? I searched related question in Stack Overflow but these aren't helpful. Below is my code:
MainActivity.java (This holds all Fragments)
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
ImageButton img_boy, img_girl, img_dog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
img_boy = (ImageButton) findViewById(R.id.img_boy);
img_boy.setOnClickListener(this);
img_girl = (ImageButton) findViewById(R.id.img_girl);
img_girl.setOnClickListener(this);
img_dog = (ImageButton) findViewById(R.id.img_dog);
img_dog.setOnClickListener(this);
Boolean isFirstRun = getSharedPreferences("Preference", MODE_PRIVATE).getBoolean("isFirstRun", true);
if (isFirstRun) {
AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.Dark_theme);
builder.setTitle(R.string.chooselanguage).setItems(R.array.language, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
switch (i) {
case 1:
SharedPreferences ensharedPreferences = getSharedPreferences("selectedLanguage", Context.MODE_PRIVATE);
SharedPreferences.Editor eneditor = ensharedPreferences.edit();
eneditor.putString("language", "en");
eneditor.commit();
case 2:
SharedPreferences npsharedPrefrences = getSharedPreferences("selectedLanguage", Context.MODE_PRIVATE);
SharedPreferences.Editor npeditor = npsharedPrefrences.edit();
npeditor.putString("language", "ne");
npeditor.commit();
break;
}
}
}).setCancelable(false).create().show();
getSharedPreferences("Preference", MODE_PRIVATE).edit().putBoolean("isFirstRun", false).commit();
}
}
public void onBackPressed() {
CallForBackButton();
}
private void CallForBackButton() {
int count = getFragmentManager().getBackStackEntryCount();
switch (count) {
case 0:
QuitDialog();
break;
default:
getFragmentManager().popBackStack();
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.settings:
startActivity(new Intent(MainActivity.this, Settings.class));
break;
case android.R.id.home:
CallForBackButton();
break;
case R.id.exit:
QuitDialog();
}
return true;
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.img_boy:
Recycler rc = new Recycler();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_container, rc);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
break;
// other case
}
}
Settings.java
public class Settings extends AppCompatActivity {
public static final String DEFAULT = "N/A";
Switch aSwitch, aSwitch2;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
aSwitch = (Switch) findViewById(R.id.swic);
aSwitch2 = (Switch) findViewById(R.id.swic2);
SharedPreferences sharedPreferences = getSharedPreferences("selectedLanguage", Context.MODE_PRIVATE);
String s1 = sharedPreferences.getString("language", DEFAULT);
if (s1.matches("ne")) {
aSwitch.setChecked(true);
} else {
aSwitch.setChecked(false);
}
aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (aSwitch.isChecked()) {
SharedPreferences npsharedPreferences = getSharedPreferences("selectedLanguage", Context.MODE_PRIVATE);
SharedPreferences.Editor npeditor = npsharedPreferences.edit();
npeditor.putString("language","ne");
npeditor.commit();
aSwitch.setChecked(true);
Toast.makeText(Settings.this, "Nepali Language Selected", Toast.LENGTH_LONG).show();
} else {
SharedPreferences ensharedPreferences = getSharedPreferences("selectedLanguage", Context.MODE_PRIVATE);
SharedPreferences.Editor eneditor = ensharedPreferences.edit();
eneditor.putString("language","en");
eneditor.commit();
Toast.makeText(Settings.this, "English Language Selected", Toast.LENGTH_LONG).show();
aSwitch.setChecked(false);
}
}
});
}
}
Recycler.java (This is RecyclerView where I put text to display)
public class Recycler extends Fragment {
private List<Name> names;
RecyclerView rv;
String[] nameCollection;
public static final String DEFAULT = "N/A";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.recyclerview, container, false);
rv = (RecyclerView) view.findViewById(R.id.rv);
nameCollection = getActivity().getResources().getStringArray(R.array.babies_names);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
rv.setHasFixedSize(true);
initializeData();
initializeAdapter();
return view;
}
private void initializeAdapter() {
rvadapter adapter = new rvadapter(names);
rv.setAdapter(adapter);
}
public void initializeData() {
names = new ArrayList<>();
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("selectedLanguage", Context.MODE_PRIVATE);
String pine= sharedPreferences.getString("language", DEFAULT);
String languageToLoad=pine;
Locale locale=new Locale(languageToLoad);//Set Selected Locale
Locale.setDefault(locale);//set new locale as default
Configuration config = new Configuration();//get Configuration
config.locale = locale;//set config locale as selected locale
getActivity().getResources().updateConfiguration(config, getActivity().getResources().getDisplayMetrics());
for (int i = 0; i < nameCollection.length; i++) {
names.add(new Name(nameCollection[i]));
}
}
}
I just need to fix the language as selected by user.
One more thing, if I exit the app but not close from recent apps then, if I again go back to my app then everything works fine, languages also changes on menu(onOptionMenu). I think the quick fix for this is saving it in savedInstanceState but I am not sure and I don't know how to use that in my case.
I call Locale under MainActivity.java on onStart() callback instead of calling in instalizeData() on recyclerView and now everything working fine :D

Shared-preferences working just with Fragment Activity

I have this Fragment Activity which is my main activity and include 2 Fragment Activity.
/** SharedPreferences */
public static final String MyPREFERENCES = "MyPrefs";
SharedPreferences sharedpreferences;
int currentOrientation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
/** Rotation SharedPreferences */
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(this);
int orienation = preferences.getInt("orientation", -1);
if (orienation != -1) {
setRequestedOrientation(orienation);
}
/** End */
mAdapter = new FragmentAdapter(getSupportFragmentManager());
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mIndicator = (TitlePageIndicator) findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (outState == null) {
outState = new Bundle();
}
outState.putInt("currentOrientation",
Integer.valueOf(currentOrientation));
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
currentOrientation = savedInstanceState.getInt("currentOrientation");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menus, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
/** Rotation */
case R.id.menuRotate:
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(this);
Editor editor = preferences.edit();
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
editor.putInt("orientation",
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
editor.putInt("orientation",
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
editor.commit();
break;
}
return false;
}
}
I had set the orientation option in the menu.
The user can change the orientation from the menu to be in landscape or portrait.
Its working nice, BUT the problem is the other activities.
How can I read from the shared-preferences that I'v already declared in my main activity
what I want is that all activities in my app get the same orientation what the users choice from the menu.
This is one of my other activity:
public class MainList extends Activity {
LinearLayout b1;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_list);
b1 = (LinearLayout) findViewById(R.id.list_a);
b1.setOnClickListener(mb1);
}
View.OnClickListener mb1 = new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(MainList.this, List_1.class));
}
};
Thanks in Advance :)
So, in each you should be using the same context and not just "this".
private Context context;
public void onCreate(){
super.onCreate();
context = getApplicationContext();
}
public static Context getAppContext() {
return context;
}
You can make this context accessible by other classes that do not have a type (just function holders).
Then, in your use of Shared Prefs :
final SharedPreferences prefList = context.getSharedPreferences(
Constants.PREFERENCE_NAME, Context.MODE_PRIVATE);
If everyone is using getApplicationContext() then they will be able to talk to one another as they are all using the same Context. I would always suggest that you use Context.MODE_PRIVATE unless you need external applications to be able to grab information from those SharedPreferences.

SharedPreference not recreating menu

I'm trying to use SharedPreferences to store a preference, then change the default checked state of the menu item based on the SharedPreference. But it does not seem to be working. The menu choice stays until the app is closed. When I reload the app, the setting is back to the default, instead of the new SharedPreference setting.
public class MainActivity extends Activity {
boolean prefs = true;
String FILENAME = "settings";
String string;
public static final String LOG_TAG = "dbryant423";
public static final String PREFS_NAME = "settings";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.v(LOG_TAG, "prefs value: " +prefs);
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String preference = settings.getString("preference", string);
if (preference == "us")
menu.findItem(R.id.menu_us).setChecked(true);
else if (preference == "metric")
menu.findItem(R.id.menu_metric).setChecked(true);
return true;
}
// called when an item is selected
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) { // decide which MenuItem was pressed based on it's id
case R.id.menu_us:
menuUS();
case R.id.menu_metric:
menuMetric();
}
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
if (prefs == true)
menu.findItem(R.id.menu_us).setChecked(true);
else if (prefs == false)
menu.findItem(R.id.menu_metric).setChecked(true);
return true;
}
public void menuUS() {
prefs = true;
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("preference", "us");
editor.commit();
}
public void menuMetric() {
prefs = false;
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("preference", "metric");
editor.commit();
}
public void calculateCylinder(View v) {
Intent calculateCylinderUS = new Intent(this, CalculateCylinder.class);
Intent calculateCylinderMetric = new Intent(this, CalculateCylinderMetric.class);
Log.v(LOG_TAG, "prefs value: " +prefs);
if (prefs == true)
startActivity(calculateCylinderUS);
else if (prefs == false)
startActivity(calculateCylinderMetric);
}
Please note that onPrepareOptionsMenu gets called just before the menu is displayed to the user.
Looking at your code you are calling setChecked(true) on R.id.menu_us and R.id.menu_metric based on local variable prefs whose value will always be true whenever the activity is created. So in order to persist these states we must update menu-items based on preference values and not based on values of local variable.
I think you'd rather modify your onPrepareOptionsMenuand onCreateOptionsMenu functions as below and give it a try:
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String preference = settings.getString("preference", string);
if (preference == "us")
menu.findItem(R.id.menu_us).setChecked(true);
else if (preference == "metric")
menu.findItem(R.id.menu_metric).setChecked(true);
return true;
}
Don't compare string variables by == sign
here
if (preference == "us")
menu.findItem(R.id.menu_us).setChecked(true);
else if (preference == "metric")
menu.findItem(R.id.menu_metric).setChecked(true);
instead use .equals()
if (preference.equals("us"))
menu.findItem(R.id.menu_us).setChecked(true);
else if (preference.equals("metric"))
menu.findItem(R.id.menu_metric).setChecked(true);
I used a little bit from both answers, and I found some missing pieces myself. One of the main problems I figured out, is that I did not have a "break;" in my switch statement, and it was running both cases, no matter which one I selected. The other final fix was instead of calling
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String preference = settings.getString("preference", string);
if (preference.equals("us"))
menu.findItem(R.id.menu_us).setChecked(true);
else if (preference.equals("metric"))
menu.findItem(R.id.menu_metric).setChecked(true);
return true;
}
in which my if/else if statements are trying to modify the setChecked attribute, I realized all I needed to do was modify the value of "prefs" instead in the onCreateOptionsMenu. like so:
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String preference = settings.getString("preference", string);
if (preference.equals("us"))
prefs = true;
else if (preference.equals("metric"))
prefs = false;
return true;
}
The onPrepareOptionsMenu still needs the "setChecked" in order to switch which choice has been selected.
here is the updated working code:
public class MainActivity extends Activity {
boolean prefs = true;
String FILENAME = "settings";
String string;
public static final String LOG_TAG = "dbryant423";
public static final String PREFS_NAME = "settings";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.v(LOG_TAG, "prefs value onCreate: " +prefs);
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String preference = settings.getString("preference", string);
if (preference.equals("us"))
prefs = true;
else if (preference.equals("metric"))
prefs=false;
return true;
}
// called when an item is selected
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) { // decide which MenuItem was pressed based on it's id
case R.id.menu_us:
menuUS();
break;
case R.id.menu_metric:
menuMetric();
break;
}
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
SharedPreferences settings = getSharedPreferences(PREFS_NAME,0);
String preference = settings.getString("preference", string);
if (preference.equals("us"))
menu.findItem(R.id.menu_us).setChecked(true);
else if (preference.equals("metric"))
menu.findItem(R.id.menu_metric).setChecked(true);
return true;
}
public void menuUS() {
prefs = true;
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("preference", "us");
editor.commit();
Log.v(LOG_TAG, "prefs value menuUS: " +prefs);
}
public void menuMetric() {
prefs = false;
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("preference", "metric");
editor.commit();
Log.v(LOG_TAG, "prefs value menuMetric: " +prefs);
}
public void calculateCylinder(View v) {
Intent calculateCylinderUS = new Intent(this, CalculateCylinder.class);
Intent calculateCylinderMetric = new Intent(this, CalculateCylinderMetric.class);
Log.v(LOG_TAG, "prefs value calculateCylinder: " +prefs);
if (prefs == true)
startActivity(calculateCylinderUS);
else if (prefs == false)
startActivity(calculateCylinderMetric);
}

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

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>

Categories

Resources