I want to change the theme of my app by a switch button. There is no problem and the theme changes into dark or light as I hit the button. on the other hand, I want to change the background image as the theme changes in different activities. I mean the MainActivity has an image background and other activities have their own background image. I would be very grateful if there is a guy to help me.
this is my code:
private Switch mySwitch;
#Override
protected void onCreate(Bundle savedInstanceState) {
if(AppCompatDelegate.getDefaultNightMode() ==
AppCompatDelegate.MODE_NIGHT_YES){
setTheme(R.style.darkTheme);
}
else {setTheme(R.style.AppTheme);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mySwitch = (Switch) findViewById(R.id.my_switch);
if(AppCompatDelegate.getDefaultNightMode() ==
AppCompatDelegate.MODE_NIGHT_YES){
mySwitch.setChecked(true);
}else {
}
mySwitch.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b)
{
if(b){AppCompatDelegate.setDefaultNightMode
(AppCompatDelegate.MODE_NIGHT_YES);
restartApp();
}
else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
restartApp();
}
}
});
}
public void restartApp(){
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
finish();
}
}
Saving content in sharedPref
private SharedPreferences mSharedPreferences;
public SharedCache(SharedPreferences sharedPreferences) {
mSharedPreferences = sharedPreferences;
}
public String getThemeName() {
return mSharedPreferences.getString(THEME_NAME, APP_DARK);
}
public void setThemeName(#NonNull String theme) {
mSharedPreferences.edit().putString(THEME_NAME, theme).apply();
}
Here AppDark is my current theme name , you can set your theme name onChange of your theme .
In Activity onCreate method , get the theme from sharedPref . Or you can follow the below link for better understanding on sharedPreference . https://medium.com/android-grid/android-sharedpreferences-example-writing-and-reading-values-7a677f4448c3
Related
I am new to android. I am creating a app which uses a toggle button. I want the toggle button to do some tasks when the button is in checked state and do some another tasks when the button is unchecked. And I want the toggle button to retain its state even when the user closes the app(by pressing back switch) and comes back. I managed to get it done by using shared preference, but the problem is that when the user turns the toggle button on and goes back and come back again, the tasks are getting done again. Is there any way to retain my toggle button on state, and not to the tasks associated with it?? And sorry for my bad English :)
public class MainActivity extends AppCompatActivity {
ToggleButton onoff;
public static Bundle bundle=new Bundle();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
onoff = (ToggleButton) findViewById(R.id.toggleButton);
onoff.setChecked(false);
onoff.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// do some tasks here
} else {
//do some tasks here
}
}
});
}
#Override
public void onPause(){
super.onPause();
bundle.putBoolean("ToggleButtonState", onoff.isChecked());
}
#Override
public void onResume(){
super.onResume();
if(bundle.getBoolean("ToggleButtonState",false))
{
onoff.setChecked(true);
}
}
}``
Simply add another condition to your OnCheckedChangeListener:
onoff.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked && !bundle.getBoolean("ToggleButtonState",false) {
// do some tasks here
} else if(!isChecked){ //optional + , your preference on what to to :)
//do some tasks here
}
}
});
So, when you return, and your button is checked, but your saved boolean is also true, it will not execute your task.
Edit:
For use with onSaveInstanceState :
In your activity, add the following method:
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean("ToggleButtonState", onoff.isChecked());
super.onSaveInstanceState(outState);
}
And retrieve this boolean in onCreate(), under findViewById(...):
boolean checkedStatus = savedInstanceState.getBoolean("ToggleButtonState", false);
onoff.setChecked(checkedStatus);
For additional Information visit Recreating an Activity
I have two activities. In the second activity I have a spinner. what I would like to happen is after the user selects an item from the spinner it will save via actionbar press and on back press which will load the previous activity. Based on my research my activity is supposed to look something like the following below but it's not working what am I doing wrong??
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit);
getActionBar().setDisplayHomeAsUpEnabled(true);
spin = (Spinner)findViewById(R.id.editspin);
Intent i = this.getIntent();
note = new ArgueItem();
note.setKey(i.getStringExtra("key"));
note.setText(i.getStringExtra("text"));
EditText et = (EditText)findViewById(R.id.argueEdit);
et.setText(note.getText());
et.setSelection(note.getText().length());
}private boolean saveState() {
prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor prefEditor = prefs.edit();
int daddy = spin.getSelectedItemPosition();
prefEditor.putInt("savedValue",daddy);
prefEditor.commit();
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
EditText et = (EditText)findViewById(R.id.argueEdit);
String argueText = et.getText().toString();
if(argueText.equals("")){
Toast.makeText(this, "Please Enter A New ", Toast.LENGTH_SHORT).show();
return false;
}
if (item.getItemId() == android.R.id.home) {
saveAndFinish();
}
return false;
}
#Override
public void onBackPressed() {
EditText et = (EditText)findViewById(R.id.argueEdit);
String argueText = et.getText().toString();
if(argueText.equals("")){
Toast.makeText(this, "Please Enter A New ", Toast.LENGTH_SHORT).show();
return;
}else{
saveAndFinish();
}
In your second activity, you have to override the onPause() and. Inside it write the saving process.
protected void onPause(){
super.onPause();
//Include the code which, save the data.
}
You should use a FragmentActivity and add/remove fragments within the same activity.
check these resources:
http://developer.android.com/guide/components/fragments.html
http://www.vogella.com/articles/AndroidFragments/article.html
This is how i'm initializing my spinner which is in the ActionBar. I'm not adding it as a custom view, but I'm using the drop down menu feature.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
actionBar.setListNavigationCallbacks(adapter, new ActionBar.OnNavigationListener() {
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
//save in preferences
PreferenceManager.getDefaultSharedPreferences(MainActivity.this).edit().
putInt(SELECTED_DIARY_PREF, itemPosition).commit();
return true;
}
});
int selPosition = PreferenceManager.getDefaultSharedPreferences(this).getInt(SELECTED_DIARY_PREF, 0);
actionBar.setSelectedNavigationItem(selPosition);
What this code does is: saving the preference when an item of the menu is clicked, and restoring that preference when the activity is launched. Hope it helps.
I have a EditText in a preference menu that allows me to edit a URL address. The problem is when I get the preference value in the mainActivity is not getting updated right away after I click OK in the Preference Menu. Not sure how to fix this problem. I tried a bunch of ideas and finally decided to ask.
public class PreferencesActivityTest extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.radio_preferences);
PreferenceManager.setDefaultValues(PreferencesActivityTest.this,
R.xml.radio_preferences, false);
EditTextPreference editPref =(EditTextPreference)findPreference("MyText");
editPref.setOnPreferenceChangeListener(
new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
if (newValue.toString().length() > 0) {
return true;
}
// If now create a message to the user
Toast.makeText(PreferencesActivityTest.this,
"Invalid Input", Toast.LENGTH_SHORT).show();
return false;
}
});
}
}
PS: This code updates the newValue to what I enter in the EditTextPreference, doesn't carry the new value to the MainActivity until I modify it again...
UPDATE:
In OnResume() I can see that the value is updated with the one that I modified in the PreferenceActivityTest from EditTextPreference. What I'm trying to do is to pass this newValue into the SetDataSource("").
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_radio);
initializeMediaPlayer();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_edit:
editURL();
// make a Dialog or show an Activity
return true;
}
}
private void initializeMediaPlayer() {
PreferenceManager.setDefaultValues(this, R.xml.radio_preferences, false);
SharedPreferences pref =PreferenceManager.getDefaultSharedPreferences(this);
String radioPath = pref.getString("MyText", "default value");
// Toast.makeText(this, radioPath, Toast.LENGTH_SHORT).show();
try {
radioPlayer.reset();
// radioPlayer.setDataSource("http://31.xx.xxx");
// Toast.makeText(this, radioPath, Toast.LENGTH_SHORT).show();
radioPlayer.setDataSource(radioPath);
} catch {
}
}
public void editURL() {
stopPlaying();
startActivity(new Intent(getBaseContext(), PreferencesActivityTest.class));
}
I am doing something fundamentally wrong but I need help. Thank you in advance !
how are you calling the preference activity? If you are calling it directly, you probably need to change the call to startActivityForResult so you refresh your data once you return from the Activity
I have a tabhost with three activities and I want to save the pressed state of the buttons of each activity
So now How can I save the pressed state of each button in all three child activities so that when I move from one activity to the other the button pressed state will be reflected on moving back. first activity -> all 4 buttons pressed -> go to 2nd activity -> come back to first activity -> all buttons in first activity should be in pressed state
When I go to second child tab and come to the first child tab the change(The buttons which I pressed are not in pressed state) is not reflecting
Help is always appreciated , Thanks
this is my code in first tabhost child activity
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
seatdirnbtn.setOnClickListener(listner1);
seatdirnbtn1.setOnClickListener(listner2);
seatdirnbtn.setPressed(true);
seatdirnbtn1.setPressed(true);
this.LoadPreferences();
}
private void SavePreferences() {
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("sharedPreferences",MODE_WORLD_READABLE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("state", seatdirnbtn.isEnabled());
editor.putBoolean("state1", seatdirnbtn1.isEnabled());
editor.commit();
}
private void LoadPreferences() {
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("sharedPreferences",MODE_WORLD_READABLE);
Boolean state = sharedPreferences.getBoolean("state", false);
Boolean state1 = sharedPreferences.getBoolean("state1", false);
seatdirnbtn.setPressed(state);
seatdirnbtn1.setPressed(state1);
}
#Override
protected void onStart() {
super.onStart();
LoadPreferences();
}
#Override
protected void onPause() {
SavePreferences();
super.onPause();
}
public static boolean isclick = false;
private View.OnClickListener listner1 = new View.OnClickListener() {
public void onClick(View v) {
if (isclick) {
seatdirnbtn.setBackgroundResource(R.drawable.icon4hlt);
} else {
seatdirnbtn.setBackgroundResource(R.drawable.icon4);
}
isclick = !isclick;
}
};
private View.OnClickListener listner2 = new View.OnClickListener() {
public void onClick(View v) {
if (isclick) {
seatdirnbtn1.setBackgroundResource(R.drawable.icon2hlt);
} else {
seatdirnbtn1.setBackgroundResource(R.drawable.icon2);
}
isclick = !isclick;
}
};
probably you should override onResume() method in which you should set buttons states. this method is called after onCreate() and even the activity is already created. If you have activities in tabHost they are not created each time you switch between tabs so onCreate() method will be called only once but onResume() every time you switch to tab with particular activity.
your code which is loading preferences is in onStart() method. Look here on activity lifecycle. You can see that this method is called only if your activity was stopped before but will never called if it was just paused.
EDIT:
if you have just 2 states like in your code from question it could be better to use ToggleButton which also generally have 2 states. You can style it to have different backgrounds for each state. This tutorial could be helpfull.
Than you will have a little bit different Listener:
toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if(checked) {
//do sth if it's checked
} else {
//do sth if it's not checked;
}
}
});
to change states for them programatically:
toggleButton.setChecked(true); //or false
so finally you can save this state to SharedPreferences:
editor.putBoolean("toggleButton1",toggleButton.isChecked());
and when you will need this state:
boolean isChecked = sharedPreferences.getBoolean("toggleButton1",false);
toggleButton.setChecked(isChecked);
selector will take care of switching button backgrounds for each state.
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.