Android enabled preferences are grayed out - android

Trying to create Android settings with preferences, which some of them open new Activity / custom Dialog with OnPreferenceClickListener. Everything is working fine, but the problem is that on real device, random preferences have gray colour like they are disabled. I am not able to find any pattern, why it is happening, but it only happens with clean Preference class. EditTextPreferences and others do not have this kind of problem. Here is example with some code.
<PreferenceCategory
app:title="#string/extra"
app:key="annots">
<Preference
app:key="annot"
app:title="#string/pref_annotation" />
<Preference
app:key="reset"
app:title="#string/reset_extra" />
</PreferenceCategory>
<PreferenceCategory
app:title="#string/app"
app:key="version_android">
<Preference
app:key="about_app"
app:title="#string/third_party"/>
<Preference
app:key="show_web"
app:title="#string/website"/>
<Preference
app:key="pref_about_build"
app:persistent="false"
app:selectable="false"
app:title="#string/build_version" />
</PreferenceCategory>
Whole Java code:
public class SettingsActivity extends AppCompatActivity {
Context context;
public final static String GPS_DIS = "GPS_distance", GPS_TIME = "GPS_time", FILESIZE = "file_size", SAMPLING = "sampling_frequency", SAMPLING_WEAR = "sampling_frequency_wear";
public final static String FREE_MEMORY_PHONE_TO_SAVE = "free_memory_phone", FREE_MEMORY_WEAR_TO_SAVE = "free_memory_wear";
public final static String ACTIVITY_RECOGNITION_INTERVAL = "activity_recognition_refresh";
private final static String AVAILABLE_MEMORY = "available_memory";
public final static String AVAILABLE_MEMORY_WEAR = "available_memory_wear";
private static int getDelay(int rate) {
int delay = 0;
switch (rate) {
case SENSOR_DELAY_FASTEST:
break;
case SENSOR_DELAY_GAME:
delay = 20000;
break;
case SENSOR_DELAY_UI:
delay = 66667;
break;
case SENSOR_DELAY_NORMAL:
delay = 200000;
break;
}
return delay;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(getString(R.string.settings));
context = this;
setContentView(R.layout.activity_settings);
getSupportFragmentManager().beginTransaction()
.replace(R.id.settings_container, new PreferencesFragmentNew())
.commit();
if(getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
finish();
startActivity(new Intent(this, Main.class));
return true;
}
public static class PreferencesFragmentNew extends PreferenceFragmentCompat {
private ArrayList<String> setDigits = new ArrayList<String>(){{
add(GPS_DIS);
add(GPS_TIME);
add(FILESIZE);
add(ACTIVITY_RECOGNITION_INTERVAL);
add(FREE_MEMORY_PHONE_TO_SAVE);
add(FREE_MEMORY_WEAR_TO_SAVE);
}};
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.prefs, rootKey);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(Objects.requireNonNull(getActivity()));
findPreference(SAMPLING).setSummary(getDelay(preferences.getInt(SAMPLING, 0)) +" μs");
findPreference(SAMPLING).setOnPreferenceClickListener(preference -> {
DialogsOther.infoDialog(getContext(), DialogsOther.SAMPLING);
return true;
});
findPreference(SAMPLING_WEAR).setSummary(getDelay(preferences.getInt(SAMPLING_WEAR, 2)) +" μs");
findPreference(SAMPLING_WEAR).setOnPreferenceClickListener(preference -> {
DialogsOther.infoDialog(getContext(), DialogsOther.SAMPLING_WEAR);
return true;
});
findPreference(AVAILABLE_MEMORY).setSummary(Memory.getFreeMemoryString());
String memoryWear = preferences.getString(AVAILABLE_MEMORY, "");
if(memoryWear.equals("")){
findPreference(AVAILABLE_MEMORY_WEAR).setSummary(getContext().getString(R.string.unknown));
}else{
findPreference(AVAILABLE_MEMORY_WEAR).setSummary(getContext().getString(R.string.last_known)+" "+memoryWear+" MB");
}
for(String s : setDigits){
EditTextPreference editTextPreference = findPreference(s);
if(editTextPreference != null) {
editTextPreference.setOnBindEditTextListener(editText -> editText.setInputType(InputType.TYPE_CLASS_NUMBER));
}
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
editTextPreference.setSummary(sharedPreferences.getString(s, ""));
}
// resetting to default values - annotations
findPreference("reset").setOnPreferenceClickListener(preference -> getContext().sendBroadcast(new Intent(Main.RESET_STATS)));
Preference pref = findPreference("activity_recognition_refresh");
pref.setOnPreferenceChangeListener((preference, newValue) -> {
preference.setSummary(newValue + " s");
return true;
});
findPreference("activity_recognition_about").setOnPreferenceClickListener(preference -> {
DialogsOther.infoDialog(getContext(), R.string.title_activity_recognition,
R.string.about_activity_recognition_text).show();
return true;
});
findPreference("about_app").setOnPreferenceClickListener(preference -> {
startActivity(new Intent(getActivity(), AboutApp.class));
return true;
});
findPreference("annot").setOnPreferenceClickListener(preference -> {
startActivity(new Intent(getActivity(), AnnotationActivitySet.class));
return true;
});
findPreference("show_web").setOnPreferenceClickListener(preference -> {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("..."));
startActivity(browserIntent);
return true;
});
findPreference("pref_about_build").setSummary(BuildConfig.VERSION_NAME);
}
}
#Override
public void onBackPressed() {
finish();
startActivity(new Intent(this, Main.class));
}
}
The last one should be with gray color, but this happens and every time it is random:
I tried to change styles of preferences, their colours, set enabled programmatically, tried multiple phones with different versions of Android. Any suggestion / quick fix ? Or should I create own implementation.

Related

Android restart fragment after changing preference

I have a Spinner where various values update a TextView. For example, 0 (which is default) on the Spinner shows "- min", whereas 12 shows "60 min" in the TextView. This Spinner is inside a Fragment which is inside TabLayout in activity_main. I have a PreferenceFragment (which is inside a normal Activity, because I get toolbar overlappings when using FragmentActivity. The Activity can be called via a menu.) where I can set the time unit to hours or minutes. In my example above, the setting is minutes.
When I change minutes to hours, I want the TextView to change to "- hr" when I leave the PreferenceFragment and return to the main activity. This only works when I restart the app, but I think it should be possible to do this without a restart. Here's my code.
MyApplication.java
public class MyApplication extends Application {
#Override
public void onCreate() {
PreferenceManager.setDefaultValues(this, R.xml.user_settings, false);
super.onCreate();
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
String time = settings.getString("TIME", "");
if ("".equals(time)) {
settings.edit().putString("TIME", "2").commit();
} else if ("1".equals(time)) {
settings.edit().putString("TIME", "1").commit();
} else if ("2".equals(time)) {
settings.edit().putString("TIME", "2").commit();
}
}
}
activity_settings.xml
<fragment
android:id="#+id/fragment_settings"
android:name="com.arjendejong.ovengevormdglas.SettingsFragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#id/toolbar" />
user_settings.xml
<ListPreference
android:defaultValue="2"
android:entries="#array/time_unit"
android:entryValues="#array/listTimeValues"
android:key="time_unit"
android:title="#string/time_unit" />
SettingsFragment.java
public class SettingsFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.user_settings);
ListPreference timeUnitPref = (ListPreference) findPreference("time_unit");
timeUnitPref.setSummary(timeUnitPref.getEntry());
timeUnitPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object o) {
preference.setSummary(o.toString());
return true;
}
});
ListPreference timeUnitPreference = (ListPreference) findPreference("time_unit");
timeUnitPreference.setOnPreferenceChangeListener(timeUnitChangeListener);
}
Preference.OnPreferenceChangeListener timeUnitChangeListener = new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
ListPreference timeUnitPref = (ListPreference)findPreference("time_unit");
switch (newValue.toString()) {
case "1":
PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext()).edit().putString("TIME", "1").commit();
timeUnitPref.setSummary(timeUnitPref.getEntry());
Toast.makeText(getActivity().getBaseContext(), "UREN", Toast.LENGTH_LONG).show();
Log.d("DEBUG","UREN");
timeUnitPref.setSummary(R.string.time_hours);
break;
case "2":
PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext()).edit().putString("TIME", "2").commit();
timeUnitPref.setSummary(timeUnitPref.getEntry());
Toast.makeText(getActivity().getBaseContext(), "MINUTEN", Toast.LENGTH_LONG).show();
Log.d("DEBUG","MINUTEN");
timeUnitPref.setSummary(R.string.time_minutes);
break;
/*default:
PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext()).edit().putString("TIME", "2").commit();
timeUnitPref.setSummary(timeUnitPref.getEntry());
Toast.makeText(getActivity().getBaseContext(), R.string.save_language_changes, Toast.LENGTH_LONG).show();
timeUnitPref.setSummary(R.string.time_minutes);
break;*/
}
return true;
}
};
}
TabFragment
public class TabFragment2 extends Fragment {
TextView seekBarValue,iniCoolTimeValue, secCoolTimeValue, thirdCoolTimeValue;
Double sum;
private SharedPreferences pref;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab_fragment_2, container, false);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity().getBaseContext());
String time = settings.getString("TIME", "");
seekBarValue = (TextView)v.findViewById(R.id.seekBarValue);
iniCoolTimeValue = (TextView)v.findViewById(R.id.iniCoolTimeValue);
secCoolTimeValue = (TextView)v.findViewById(R.id.secCoolTimeValue);
thirdCoolTimeValue = (TextView)v.findViewById(R.id.thirdCoolTimeValue);
SeekBar seekBar = (SeekBar)v.findViewById(R.id.seekBar);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
seekBarValue.setText(String.valueOf(progress));
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity().getBaseContext());
String time = settings.getString("TIME", "");
if (progress >= 0 && progress < 1) {
if(time.equals("1")) {
iniCoolTimeValue.setText("- hr");
secCoolTimeValue.setText("- hr");
thirdCoolTimeValue.setText("- hr");
} else if(time.equals("2")){
iniCoolTimeValue.setText("- min");
secCoolTimeValue.setText("- min");
thirdCoolTimeValue.setText("- min");
}
}
else if (progress >= 1 && progress < 13) {
if( time.equals("1")){
sum = (482.0-427.0)/55.0;
DecimalFormat sumResult = new DecimalFormat("0.0");
iniCoolTimeValue.setText(sumResult.format(sum) + " hr");
sum = (427.0-371.0)/99.0;
DecimalFormat sumResult2 = new DecimalFormat("0.0");
secCoolTimeValue.setText(sumResult2.format(sum) + " hr");
sum = (371.0-21.0)/330.0;
DecimalFormat sumResult3 = new DecimalFormat("0.0");
thirdCoolTimeValue.setText(sumResult3.format(sum) + " hr");
} else if(time.equals("2")){
sum = (482.0 - 427.0) / 55.0 * 60.0;
DecimalFormat sumResult = new DecimalFormat("0");
sumResult.setRoundingMode(RoundingMode.HALF_UP);
iniCoolTimeValue.setText(sumResult.format(sum) + " min");
sum = (427.0 - 371.0) / 99.0 * 60.0;
DecimalFormat sumResult2 = new DecimalFormat("0");
sumResult.setRoundingMode(RoundingMode.HALF_UP);
secCoolTimeValue.setText(sumResult2.format(sum) + " min");
sum = (371.0 - 21.0) / 330.0 * 60.0;
DecimalFormat sumResult3 = new DecimalFormat("0");
sumResult.setRoundingMode(RoundingMode.HALF_UP);
thirdCoolTimeValue.setText(sumResult3.format(sum) + " min");
}
}
}
});
if(time.equals("1")) {
iniCoolTimeValue.setText("- hr");
secCoolTimeValue.setText("- hr");
thirdCoolTimeValue.setText("- hr");
} else if(time.equals("2")) {
iniCoolTimeValue.setText("- min");
secCoolTimeValue.setText("- min");
thirdCoolTimeValue.setText("- min");
}
return v;
}
#Override
public void onResume() {
super.onResume();
registerChangeListener();
}
private void registerChangeListener () {
final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
sp.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
String time = sp.getString("TIME", "");
if ("1".equals(time)) {
sp.edit().putString("TIME", "1").commit();
Log.d("TIME UNIT", time);
} else if ("2".equals(time)) {
sp.edit().putString("TIME", "2").commit();
Log.d("TIME UNIT", time);
}
}
});
}
}
Strings
<string name="time_unit">Time unit</string>
<string-array name="time_unit">
<item name="hours">Hours</item>
<item name="minutes">Minutes</item>
</string-array>
<string-array name="listTimeValues">
<item name="hours">1</item>
<item name="minutes">2</item>
</string-array>
<string name="time_hours">Hours</string>
<string name="time_minutes">Minutes</string>
The registerChangeListener(); in onResume(); inside TabFragment2 works because when I change the setting, I see the logs appearing in the Android Monitor.
How can I reflect a settings change when I leave Preferences and return to the previous activity which is the TabFragment?
I've moved this code block from TabFragment2.java to MainActivity.java and I added recreate(); to the if-statements and now it's working!
#Override
public void onResume() {
super.onResume();
registerChangeListener();
}
private void registerChangeListener () {
final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
sp.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
String time = sp.getString("TIME", "");
if ("1".equals(time)) {
sp.edit().putString("TIME", "1").commit();
Log.d("TIME UNIT", time);
recreate();
} else if ("2".equals(time)) {
sp.edit().putString("TIME", "2").commit();
Log.d("TIME UNIT", time);
recreate();
}
}
});
}

Using Shared preferences to remember the font size that a user prefers in Android

I'm developing a mobile songbook android application. I have enabled text to be zoomed in or out. I want the application to be able to remember the specific font size that a user prefers when a user closes a specific song to another or even better even when a user closes the application and opens it again. Here is how i tried doing it:
public void saveFont(View view){
SharedPreferences sharedPref = getSharedPreferences("fontsize", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putFloat("fontsize",factor.getInt());
editor.apply();
}
public void rememberFont(View view){
SharedPreferences sharedPref = getSharedPreferences("fontsize", Context.MODE_PRIVATE);
double factor = sharedPref.getString("fontsize","");
factor.setInt();
}
Here is the entire class:
public class SongbookActivity extends AppCompatActivity {
private TextView wordMeaning;
private TextToSpeech convertToSpeech;
ScaleGestureDetector scaleGestureDetector;
public double factor;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dictionary);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarSongActivity);
TextView textViewTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
setSupportActionBar(toolbar);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
int dictionaryId = bundle.getInt("SONG._ID");
int id = dictionaryId + 1;
wordMeaning = (TextView)findViewById(R.id.dictionary);
String title = bundle.getString("SONG._TITLE");
String description = bundle.getString("SONG._LYRICS");
final android.support.v7.app.ActionBar ab = getSupportActionBar();
ab.setHomeAsUpIndicator(R.drawable.left);
ab.setTitle(null);
ab.setDisplayHomeAsUpEnabled(true);
textViewTitle.setText(title);
textViewTitle.setSelected(true);
// textViewTitle.setMovementMethod(new ScrollingMovementMethod());
wordMeaning.setTextIsSelectable(true);
registerForContextMenu(wordMeaning);
wordMeaning.setMovementMethod(new ScrollingMovementMethod());
wordMeaning.setText(description);
scaleGestureDetector = new ScaleGestureDetector(this, new simpleOnScaleGestureListener());
}
//copy text or select
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
//user has long pressed your TextView
menu.add(0, v.getId(), 0, "Song copied to Clipboard");
//cast the received View to TextView so that you can get its text
TextView yourTextView = (TextView) v;
//place your TextView's text in clipboard
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
clipboard.setText(yourTextView.getText());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getPointerCount() > 1) {
scaleGestureDetector.onTouchEvent(event);
return true;
}
return false;
}
public void saveFont(View view){
SharedPreferences sharedPref = getSharedPreferences("fontsize", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putFloat("fontsize",factor.getInt());
editor.apply();
}
public void rememberFont(View view){
SharedPreferences sharedPref = getSharedPreferences("fontsize", Context.MODE_PRIVATE);
double factor = sharedPref.getString("fontsize","");
factor.setInt();
}
public class simpleOnScaleGestureListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
#Override
public boolean onScale(ScaleGestureDetector detector) {
// TODO Auto-generated method stub
float size = wordMeaning.getTextSize();
Log.d("TextSizeStart", String.valueOf(size));
float factor = detector.getScaleFactor();
Log.d("Factor", String.valueOf(factor));
float product = size*factor;
Log.d("TextSize", String.valueOf(product));
wordMeaning.setTextSize(TypedValue.COMPLEX_UNIT_PX, product);
size = wordMeaning.getTextSize();
Log.d("TextSizeEnd", String.valueOf(size));
return true;
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
double factor = 1;
float size = wordMeaning.getTextSize();
saveFont(View view);
rememberFont(View view);
Log.d("TextSizeStart", String.valueOf(size));
switch (item.getItemId()) {
case R.id.small_layout:
factor = 0.5;
break;
case R.id.medium_layout:
factor = 0.9;
break;
case R.id.large_layout:
factor = 1.3;
break;
case R.id.xlarge_layout:
factor = 1.8;
break;
}
Log.d("Factor", String.valueOf(factor));
double product = size*factor;
Log.d("TextSize", String.valueOf(product));
wordMeaning.setTextSize(TypedValue.COMPLEX_UNIT_PX, (float)product);
size = wordMeaning.getTextSize();
Log.d("TextSizeEnd", String.valueOf(size));
return super.onOptionsItemSelected(item);
}
}
I'm getting errors when trying to call the method and on the method declaration. i'm a noob at this so please give me all the details you might think can help me, no matter how insignificant it can be.
here you will get all http://developer.android.com/training/basics/data-storage/shared-preferences.html
actually you storing in float with int and trying to get in string so try below
public void saveFont(View view){
SharedPreferences sharedPref = getSharedPreferences("fontsize", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("fontsize",factor.getInt());
editor.commit();
}
and from getting back
public void rememberFont(View view){
SharedPreferences sharedPref = getSharedPreferences("fontsize", Context.MODE_PRIVATE);
int prevFont = sharedPref.getInt("fontsize",-1);
}
in -1 you can set your default font
If you are having trouble with SharedPreferences, try using this. This greatly simplifies the whole process and uses SharedPreferences internally. All you have to do is copy the source file in your project and use it.
Here is an example:
In your activity's onCreate() method, initialize TinyDB.
TinyDB tinyDB = new TinyDB(this);
Then use it like this:
tinyDB.putString("fontSize", "12");
String fontSize = tinyDB.getString("fontSize");
As simple as that. There are many methods which are very useful in day to day development, just go through the source file once. Hope it helps.
Just a "light" how you can do this.
public void setVariable(float myFloat) {
pref = _context.getSharedPreferences("fontsize", Context.MODE_PRIVATE);
editor = pref.edit();
editor.putFloat("fontsize", myFloat);
editor.commit();
}
public float getVariable() {
pref = _context.getSharedPreferences("fontsize", Context.MODE_PRIVATE);
return pref.getFloat("fontsize", 5.5/*a default value*/);
}
_context can be an attribute.
EDIT1: This class works FINE for me to any 'save' issues. Change this as your need
public class SharedPreferencesManager {
// Shared Preferences
private SharedPreferences pref;
private SharedPreferences.Editor editor;
private Context _context;
// Shared pref mode
private final int PRIVATE_MODE_SHARED_PREF = 0;
// Shared preferences file name
private final String PREF_NAME = "blabla";
/*KEYS para o sharedpreferences*/
private final String KEY_TO_USE = PREF_NAME + "setFont";
public SharedPreferencesManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE_SHARED_PREF);
editor = pref.edit();
}
public void setFont(float keySize) {
editor.putFloat(KEY_TO_USE, keySize);
editor.commit();
}
public boolean getFont() {
return pref.getFloat(KEY_TO_USE, 15/*your default value is in here (in sp)*/);
}
}
To use this, just create an object (passing the context[the activity]) and use the method GET in EVERY call/inflate of your EditText/TextView, and set the size like this
myTextView.setTextSize(mSharedPreferencesManagerObject.getVariable())
And to all of this make sense, on EVERY zoom changes, you need to call
mSharedPreference.setVariable(sizeHere)
It HAS to work. If not, the problem is in your "OnZoomChange" logic/semantic.

Android Landscape Orientation on Fragment Resetting Shared Preferences

I am using shared preferences to keep track of a Admin code that is saved on the device, I have noticed that when I go this particular fragment that has a landscape orientation the preference gets called twice and on the second time it resets to its initial null value. this is the only fragment it happens on and i have been able to narrow it down to the line
activity.setRequestedOrientation(
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
is there a particular correct method to have shared preferences working with a landscape orientation
Here is the Code
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final Activity activity = getActivity();
SharedPreferences sharedpreferences = activity.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Boolean Admin_Mode = sharedpreferences.getBoolean("AdminCode", false);
String IPaddress = sharedpreferences.getString("IP Address", "");
System.out.println(IPaddress);
System.out.println(Admin_Mode);
View rootView = inflater.inflate(R.layout.augmented_reality_view, container, false);
ActionBar actionBar = ((ActionBarActivity)activity).getSupportActionBar();
actionBar.hide();
System.out.println("here");
activity.setRequestedOrientation(
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
mSensorManager = (SensorManager)getActivity().getSystemService(Context.SENSOR_SERVICE);
mRotationVectorSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
mMagneticSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
mSensorManager.registerListener(this, mRotationVectorSensor, 10000);
mSensorManager.registerListener(this, mMagneticSensor, 10000);
HeadTracker = (ToggleButton) rootView.findViewById(R.id.HeadTracker);
return rootView;
}
#Override
public void onSensorChanged(SensorEvent event) {
if (HeadTracker.isChecked() == true) {
if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {
SensorManager.getRotationMatrixFromVector(
mRotationMatrix, event.values);
if (mRotationMatrix[2] >= 0.6 && mRotationMatrix[0] >= -0.1 && mRotationMatrix[0] <= 0.2){
Left = true;
Right = false;
}
else if (mRotationMatrix[2] <= -0.8 && mRotationMatrix[0] >= -0.1 && mRotationMatrix[0] <= 0.2){
Left = false;
Right = true;
}
else{
Left = false;
Right = false;;
}
}
}
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
if(event.values[2] >= 390){
MagnetButtonPressed = true;
}
else{
MagnetButtonPressed = false;
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onPause()
{
super.onPause();
mSensorManager.unregisterListener(this);
}
Any Advice would be Epic :)
Cheers
Steve
///...... EDIT .........\\\
added in settings fragment code
public class Settings extends PreferenceFragment {
public SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "MyPrefs" ;
String IPaddress;
int PortNumber;
Boolean Admin_Mode;
public Settings() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View rootView = inflater.inflate(R.layout.settings, container, false);
getActivity().setRequestedOrientation(
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
final SharedPreferences sharedpreferences = getActivity().getSharedPreferences(MyPREFERENCES,Context.MODE_PRIVATE);
IPaddress = sharedpreferences.getString("IP Address","");
PortNumber = sharedpreferences.getInt("Port Numner", 1);
Admin_Mode = sharedpreferences.getBoolean("AdminCode", false);
final EditText mEdit = (EditText)rootView.findViewById(R.id.ipaddress);
final EditText mEdit2 = (EditText)rootView.findViewById(R.id.portnumber);
final EditText AdminCommandBox = (EditText)rootView.findViewById(R.id.AdminCommandBox);
mEdit.setText(IPaddress);
String strI = Integer.toString(PortNumber);
mEdit2.setText(strI);
Button clickButton = (Button) rootView.findViewById(R.id.Update_Settings);
clickButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("IP Address", mEdit.getText().toString());
editor.putInt("Port Numner", Integer.parseInt(mEdit2.getText().toString()));
editor.commit();
Toast.makeText(getActivity(),"Port and Ip Updated!",Toast.LENGTH_SHORT).show();
}
});
final Button Authorise = (Button) rootView.findViewById(R.id.Authorise_Button);
if (Admin_Mode == false){Authorise.setText("Authorise");}
else if (Admin_Mode == true){Authorise.setText("Deactivate");}
Authorise.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Admin_Mode == false){
if (AdminCommandBox.getText().toString().equals("FerasQUT123")) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean("AdminCode", true);
editor.commit();
Toast.makeText(getActivity(),"Code Authorised",Toast.LENGTH_SHORT).show();
Authorise.setText("Deactivate");
}
else{
Toast.makeText(getActivity(),"Please Enter the Correct Code",Toast.LENGTH_SHORT).show();
}
}
else if (Admin_Mode == true){
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean("AdminCode", false);
editor.commit();
Toast.makeText(getActivity()," Deactivated",Toast.LENGTH_SHORT).show();
Authorise.setText("Authorise");
}
}
});
return rootView;
}
public void onDestroy() {
super.onDestroy();
}}
In the shared preference i get the state of the admin mode at the beginning of the on create, i set it in the main activity to false and then update it in the settings fragment if the correct code is entered.
Your issue is that you are setting admin mode to false in the activity's onCreate method. When the screen orientation changes, the activity will be destroyed and recreated--so onCreate will be called again, which is setting your admin mode preference to false.

How to change background color or theme of keys dynamically in Custom Keyboard Android

I am working on Custom keyboard app I need to set or change background theme or color of keyboard .their setting.xml view in my app where user can select different background theme and different color for key rows.
during first time launch of application it is working fine but next time when custom keyboard is displaying theme is not changed.
I am using this code:
public class SoftKeyboard extends InputMethodService
implements KeyboardView.OnKeyboardActionListener {
static final boolean DEBUG = false;
/**
* This boolean indicates the optional example code for performing
* processing of hard keys in addition to regular text generation
* from on-screen interaction. It would be used for input methods that
* perform language translations (such as converting text entered on
* a QWERTY keyboard to Chinese), but may not be used for input methods
* that are primarily intended to be used for on-screen text entry.
*/
static final boolean PROCESS_HARD_KEYS = true;
private static final int SELECT_PICTURE = 101;
private KeyboardView mInputView;
private CandidateView mCandidateView;
private CompletionInfo[] mCompletions;
private Context context = SoftKeyboard.this;
private StringBuilder mComposing = new StringBuilder();
private boolean mPredictionOn;
private boolean mCompletionOn;
private int mLastDisplayWidth;
private boolean mCapsLock;
private long mLastShiftTime;
private long mMetaState;
private LatinKeyboard mSymbolsKeyboard;
private LatinKeyboard mSymbolsShiftedKeyboard;
private LatinKeyboard mQwertyKeyboard;
private LatinKeyboard mSmilyKeyboard;
private LatinKeyboard mSmilyKeyboard1;
private LatinKeyboard mCurKeyboard;
private String mWordSeparators;
/**
* Main initialization of the input method component. Be sure to call
* to super class.
*/
#Override
public void onCreate() {
super.onCreate();
mWordSeparators = getResources().getString(R.string.word_separators);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("Name","");
Log.e("SoftKeyboard - ",""+name+"OnCreate Method Called--");
if(!name.equalsIgnoreCase(""))
{
name = name+" Sethi"; /* Edit the value here*/
}
}
And This is my Setting Class where i am setting or selecting color or theme:
public class Setting extends Activity implements OnClickListener {
LinearLayout roar, edge, burst, impact, blue_theme, orange_theme,
green_theme, black_brigthness, white_brightness;
Bundle bundle;
public static boolean isblackBrightness = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.setting);
// ----------UI intilisation---------------------
uiInitilisation();
}
public void uiInitilisation() {
roar = (LinearLayout) findViewById(R.id.ror_LL);
edge = (LinearLayout) findViewById(R.id.edge_LL);
burst = (LinearLayout) findViewById(R.id.burst_LL);
impact = (LinearLayout) findViewById(R.id.impact_LL);
// -------------Themes------------------------------
blue_theme = (LinearLayout) findViewById(R.id.blue_theme_LL);
orange_theme = (LinearLayout) findViewById(R.id.orange_theme_LL);
green_theme = (LinearLayout) findViewById(R.id.green_theme_LL);
// ------------Brightness----------------------------
black_brigthness = (LinearLayout) findViewById(R.id.black_brigthness_LL);
white_brightness = (LinearLayout) findViewById(R.id.white_brigthness_LL);
// --------------On Click Events-------------------
roar.setOnClickListener(this);
edge.setOnClickListener(this);
burst.setOnClickListener(this);
impact.setOnClickListener(this);
// -----------Theme-------------------------------------
blue_theme.setOnClickListener(this);
orange_theme.setOnClickListener(this);
green_theme.setOnClickListener(this);
// ------------------Brightness--------------------------
black_brigthness.setOnClickListener(this);
white_brightness.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.ror_LL:
startActivity(new Intent(Setting.this, MainActivity.class));
break;
case R.id.edge_LL:
startActivity(new Intent(Setting.this, MainActivity.class));
break;
case R.id.burst_LL:
startActivity(new Intent(Setting.this, MainActivity.class));
break;
case R.id.impact_LL:
startActivity(new Intent(Setting.this, MainActivity.class));
break;
case R.id.blue_theme_LL:
Intent i = new Intent(Setting.this,
MainActivity.class);
i.putExtra("color", "blue");
startActivity(i);
break;
case R.id.orange_theme_LL:
Intent i2 = new Intent(Setting.this,
MainActivity.class);
i2.putExtra("color", "orange");
startActivity(i2);
break;
case R.id.green_theme_LL:
Intent i3 = new Intent(Setting.this,
MainActivity.class);
i3.putExtra("color", "green");
startActivity(i3);
break;
case R.id.black_brigthness_LL:
Intent black_britness = new Intent(Setting.this,
MainActivity.class);
black_britness.putExtra("bright", "black");
startActivity(black_britness);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Name","Harneet");
editor.commit();
isblackBrightness = true ;
Log.e("Black--","Black=="+isblackBrightness);
break;
case R.id.white_brigthness_LL:
Intent white_britness = new Intent(Setting.this,
MainActivity.class);
white_britness.putExtra("bright", "white");
startActivity(white_britness);
isblackBrightness = false;
Log.e("white--","White=="+isblackBrightness);
SharedPreferences preferences1 = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor1 = preferences1.edit();
editor1.putString("Name","Arun");
editor1.commit();
break;
}
}
}
I am not getting how to do this whether I have to set widget.
When the keyboard is shown, the framework calls onStartInputView. You can program that function to look at the values of the shared preferences and set the colors/themes appropriately on the keyboard view.
Get solution to change the layout of custom keyboard.
When keyboard first time load onCreateInputView() is called. After that when keyboard open onStartInputView(EditorInfo attribute, boolean restarting) called every time.
So, now layout of keyboard(Theme) have to define in onCreateInputView() Like This
public KeyboardView mInputView;
public View onCreateInputView() {
SharedPreferences pre = getSharedPreferences("test", 1);
int theme = pre.getInt("theme", 1);
if(theme == 1)
{
this.mInputView = (KeyboardView) this.getLayoutInflater().inflate(R.layout.input, null);
}else
{
this.mInputView = (KeyboardView) this.getLayoutInflater().inflate(R.layout.input_2, null);
}
this.mInputView.setOnKeyboardActionListener(this);
this.mInputView.setKeyboard(this.mQwertyKeyboard);
return this.mInputView;
}
and do this in onStartInputView
public void onStartInputView(EditorInfo attribute, boolean restarting) {
super.onStartInputView(attribute, restarting);
setInputView(onCreateInputView());
}

Dynamically change size of multiple textview from code (without a "on disk" xml theme)?

I have 10 TextViews in my code and i would like to change font size on all of them. On my layout i have used a #style to define common properties however i don't know how to change them all from code once layout is on screen.
What i dont want to do is update N objects but write only in one place. I know that i could use applyTheme but this assumes that you have an XML theme somewhere on disk, i want to be able to scale fonts to any size so this solution is not practical.
Any idea?
See similar questions:
How to programmatically setting style attribute in a view
android dynamically change style at runtime
android : set textView style at runtime
It sounds like its not possible to change an individual style element at runtime. You could apply a different theme, but then you would need a different theme for every font size you want to support. Annoying, but possible.
Otherwise, you have to come up with a way to reduce the pain of updating all of the textViews. You could store the size in your application class, so it is accessible by all of your activities, and then in onCreate update the size for each TextView.
Here is the whole code for dynamically change font size and theme
MainActivity:
public class MainActivity extends AppCompatActivity {
TextView textViewMain;
Button buttonChangeFont;
int size, value;
SharedPreferences pref;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pref = getApplicationContext().getSharedPreferences("MyPref", 0);
changeTheme();
setContentView(R.layout.activity_main);
//References
textViewMain = findViewById(R.id.textViewMain);
buttonChangeFont = findViewById(R.id.buttonChangeFont);
//Set Onclick on button
buttonChangeFont.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent goToPreview = new Intent(MainActivity.this, PreviewActivity.class);
startActivity(goToPreview);
}
});
int value = pref.getInt("value", 0);
textViewMain.setTextSize(value);
}
private void changeTheme() {
String theme = pref.getString("theme", "default");
if (theme != null && theme.equals("default")) {
setTheme(R.style.AppTheme);
} else if (theme != null && theme.equals("black")) {
setTheme(R.style.BlackTheme);
} else {
setTheme(R.style.BlueTheme);
}
}
public void getSize() {
editor = pref.edit();
size = getIntent().getIntExtra("size", 14);
if (size == 14) {
value = 14;
editor.putInt("value", value);
} else if (size == 20) {
value = 20;
textViewMain.setTextSize(value);
editor.putInt("value", value);
} else {
value = 30;
textViewMain.setTextSize(value);
editor.putInt("value", value);
}
editor.commit();
}
#Override
protected void onStart() {
getSize();
super.onStart();
}
}
PreviewActivity:
public class PreviewActivity extends AppCompatActivity {
TextView textViewSmall, textViewMedium, textViewLarge, textViewPreview;
Button buttonOK;
String size;
int value;
SharedPreferences pref;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pref = getApplicationContext().getSharedPreferences("MyPref", 0);
setContentView(R.layout.activity_preview);
//TextView References
textViewLarge = findViewById(R.id.textViewLarge);
textViewMedium = findViewById(R.id.textViewMedium);
textViewSmall = findViewById(R.id.textViewSmall);
textViewPreview = findViewById(R.id.textViewPreview);
//Button References
buttonOK = findViewById(R.id.buttonOK);
//Set Onclick listener to TextView and Button
textViewSmall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textViewPreview.setTextSize(14);
size = "small";
}
});
textViewMedium.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textViewPreview.setTextSize(20);
size = "medium";
}
});
textViewLarge.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textViewPreview.setTextSize(30);
size = "large";
}
});
buttonOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (size) {
case "small":
value = 14;
break;
case "medium":
value = 20;
break;
case "large":
value = 30;
break;
}
Intent i = new Intent(PreviewActivity.this, MainActivity.class);
i.putExtra("size", value);
startActivity(i);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu options from the res/menu/menu_catalog.xml file.
// This adds menu items to the app bar.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
editor = pref.edit();
// User clicked on a menu option in the app bar overflow menu
switch (item.getItemId()) {
case R.id.default_theme:
textViewPreview.setBackgroundColor(Color.WHITE);
textViewPreview.setTextColor(Color.DKGRAY);
editor.putString("theme", "default");
editor.commit();
changeTheme();
return true;
case R.id.black_theme:
textViewPreview.setBackgroundColor(Color.BLACK);
textViewPreview.setTextColor(Color.WHITE);
editor.putString("theme", "black");
editor.commit();
changeTheme();
return true;
case R.id.blue_theme:
textViewPreview.setBackgroundColor(Color.BLUE);
textViewPreview.setTextColor(Color.RED);
editor.putString("theme", "blue");
editor.commit();
changeTheme();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void changeTheme() {
String theme = pref.getString("theme", "default");
if (theme != null && theme.equals("default")) {
setTheme(R.style.AppTheme);
} else if (theme != null && theme.equals("black")) {
setTheme(R.style.BlackTheme);
} else {
setTheme(R.style.BlueTheme);
}
}
}
I am using my own custom theme. To create a custom theme you can reference this article on custom theme creation.

Categories

Resources