setTheme not changing the theme colors - android

I know this question was asked few times. but I cant find the problem in my case.
I want to change the theme of the app but my colorPrimary ,colorAccent and etc.. aren't changing.
my MainActivity extends BasicActivity. it looks like this:
public class MainActivity extends BasicActivity {
public static String MY_PREFS = "MY_PREFS";
private SharedPreferences mySharedPreferences;
int prefMode = Activity.MODE_PRIVATE;
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private ViewPagerAdapter adapter;
private TextView tabOne, tabTwo, tabThree;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
this is my BasicActivity(in this case I made it even simpler to show that the theme is taken from R.style):
public class BasicActivity extends AppCompatActivity {
public static String MY_PREFS = "MY_PREFS";
int prefMode = Activity.MODE_PRIVATE;
protected void onCreate(Bundle savedInstanceState) {
JsonParser parser = new JsonParser(getApplicationContext());
int resourceId = this.getResources().getIdentifier(parser.getThemeID(), "style", this.getPackageName());
setTheme(R.style.c_2ecc71_BC6C2B);
if (android.os.Build.VERSION.SDK_INT >= 19) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
super.onCreate(savedInstanceState);
}
}
and my XML:
<style name="c_2ecc71_BC6C2B" parent="#style/Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#2ecc71</item>
<item name="colorPrimaryDark">#1ebc61</item>
<item name="colorAccent">#BC6C2B</item>
</style>
According to the previous questions this code should work but in my case the views that have colorPrimary in their XML still loading the old theme's colors insted of the new one even though i set the theme before calling setContentView(R.layout.activity_main);
Thanks!

If you use Fragments, they will ignore the value you have set in the onCreate(), if you override the getTheme() method, it will be used within fragments as well:
Answered on different question: Change Activity's theme programmatically
#Override
public Resources.Theme getTheme() {
Resources.Theme theme = super.getTheme();
theme.applyStyle(R.style.c_2ecc71_BC6C2B, true);
return theme;
}
Use it in your MainActivity or your BasicActivity depending on where you want it to apply. You will NOT need to change it in the onCreate anymore.

You are trying to extend one of the newer themes of Android (above API 21). In addition to all the answers above , you can put your theme in styles.xml(v21).
More info here https://developer.android.com/training/material/compatibility.html

Not sure if you really want to set it programmatically, but you might try this: How to setTheme to an activity at runtime? It doesn't work call setTheme before onCreate and setContentView
If you're looking to set it for the whole application, it might be easier/cleaner to set it in the AndroidManifest.xml file instead.
<application android:theme="#style/CustomTheme">
Also, I'd highly avoid using a style name that has the values in it. The point of using a style is to avoid hard coding the values and allowing them to be configurable and reusable. What if you want to change the colorPrimary, are you also going to change your style name?

To set theme at runtime you can use following line of code :
setTheme(android.R.style.Theme_Name);
and write it before calling setContentView() and super.onCreate() method inside onCreate() method.

If you want to change that kind of stuff during runtime, you must insert all those "setTheme(android.R.style.Theme_Name);" methods inside runonUiThread, like this:
public class BasicActivity extends AppCompatActivity {
public static String MY_PREFS = "MY_PREFS";
int prefMode = Activity.MODE_PRIVATE;
protected void onCreate(Bundle savedInstanceState) {
JsonParser parser = new JsonParser(getApplicationContext());
int resourceId = this.getResources().getIdentifier(parser.getThemeID(), "style", this.getPackageName());
runOnUiThread(new Runnable() {
#Override
public void run() {
setTheme(R.style.c_2ecc71_BC6C2B);
}
});
recreate();
if (android.os.Build.VERSION.SDK_INT >= 19) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
super.onCreate(savedInstanceState);
}
}
and call recreate() after!
According to Android -
void recreate ()
Cause this Activity to be recreated with a new instance. This results in essentially the same flow as when the Activity is created due to a configuration change -- the current instance will go through its lifecycle to onDestroy() and a new instance then created after it.

Just modify your BasicActivity and MainActivity as shown in below and create appropriate theme. You can use shared preference for checking theme state during app up.
BasicActivity .java
public abstract class BasicActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
if (getLayoutID() != 0) {
setContentView(getLayoutID());
}
} catch (Exception ex) { /* ... */ }
final boolean THEME_DARK = true;// read appropriate value from SP or any other storage
Toolbar toolbar;
if ((toolbar = getToolbar()) != null) {
if (THEME_DARK/* check theme type here*/) {
toolbar.setPopupTheme(R.style.c_2ecc71_BC6C2B);
}
try {
setSupportActionBar(toolbar);
} catch (NoClassDefFoundError e) {
// Toast
finish();
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(getResources().getColor(R.color.colorPrimary));
}
}
public abstract Toolbar getToolbar();
public abstract int getLayoutID();
}
MainActivity.java
public class MainActivity extends BasicActivity {
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public Toolbar getToolbar() {
return toolbar == null ? toolbar = (Toolbar) findViewById(R.id.toolbar) : toolbar;
}
#Override
public int getLayoutID() {
return R.layout.activity_main;
}
}

You have hard-coded the theme in BaseActivity , rather than getting targetted resource id.
You need to put setTheme(value_from_resourceId);
Currently the BaseActivity always calls irrespective of value that you parsed
setTheme(R.style.c_2ecc71_BC6C2B);
than referring the runtime value

Related

Use Toolbar as ActionBar in ALL Activities without programmatically doing it in each Activity

I've placed the following code in onCreate() to set a toolbar I use in each Activity as the ActionBar:
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
This works fine and shows the back arrow and title in each Activity, and is necessary because we add custom content to our ToolBar, but it's messy and annoying to have to do this in each Activity.
What's the best way to achieve this behavior without the duplication? Can it be done in styles?
You should create Base Activity like this :
public class Base extends AppCompatActivity {
TextView icon1;
#Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
initToolbar()
}
public void initToolbar() {
.
.
.
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
if (showIcon1())
icon1.setVisibility(View.VISIBLE);
else
icon1.setVisibility(View.GONE);
}
public boolean showIcon1(){
return true;
}
And other activity :
public class OtherActivity extends Base {
#Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
}
#Override
public boolean showIcon1() {
return false;
}<br>
Hope this Help.
I'm not sure if "best" but if you really want that in all your activities you have two choices:
Inheritance: A very common Android/Java approach is to subclass Activity and then use that as your base. E.g.:
public class BaseActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupToolbar();
}
private void setupToolbar() {
// do whatever you need to do
}
}
public class YourFancyClass extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Do anything you need to. The toolbar is set by the base class.
}
}
That's one option (very popular)
Plan B would be to use Composition, mostly preferred in the iOS side, yet still very valid (and sometimes more appropriate, a discussion we're not having now) :)
Basically have an object that is capable of setting your toolbar. Create an interface that can represent that behavior. Have an implementation of such behavior (Java usually calls them XxxxxImpl and have that interface and implementation passed onto the activities that need it.
Sounds more complicated, but it's very clean and clear once you got it all together.

How do we get the theme of an Activity?

I am trying to detect the theme used for an activity but so far I am only able to find that out for the entire application? Is there a way to do this?
Just call the method getTheme() in your activity. For example.
public class MainActivity extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Theme theme = this.getTheme();
}
}
My first thought would be ContextThemeWrapper.getTheme(), since Activity extends ContextThemeWrapper

Changing the theme of an android app using preferences

I have been trying to get my app to read data from the preferences, and change the theme according to the option selected. I have found many different suggestions on the internet, including here, but have been unable to get it to work.
I have created preferences.xml and arrays.xml, and the user is able to select the theme they want. However, the change is not reflected in the app.
Here are the contents of ActivityMain.java:
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String userTheme = preferences.getString("prefTheme", "darkab");
if (userTheme.equals("darkab"))
setTheme(R.style.darkab);
else if (userTheme.equals("light"))
setTheme(R.style.light);
else if (userTheme.equals("dark"))
setTheme(R.style.dark);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#SuppressLint("NewApi")
protected void onResume(Bundle savedInstanceState) {
recreate();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String userTheme = preferences.getString("prefTheme", "darkab");
if (userTheme.equals("darkab"))
setTheme(R.style.darkab);
else if (userTheme.equals("light"))
setTheme(R.style.light);
else {setTheme(R.style.dark);}
super.onResume();
setContentView(R.layout.activity_main);
}
These are the styles I wish to use, as set in styles.xml:
<style name="darkab" parent="android:Theme.Holo.Light.DarkActionBar"></style>
<style name="light" parent="android:Theme.Holo.Light"></style>
<style name="dark" parent="android:Theme.Holo">
And here is my preferences.java file:
public class Preferences extends PreferenceActivity {
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
Any help would be appreciated.
setTheme() is effective only before the layout has been constructed i.e. you should call it before setContentView(). The LayoutInflater resolves theme attributes and accordingly set properties on the View's it creates. To apply a theme on an already running Activity, you would have to re-start the Activity.
I know that I am late but I would like to post a solution here:
Check the full source code here.
This is the code I used when changing theme using preferences..
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(this);
String themeName = pref.getString("prefSyncFrequency3", "Theme1");
if (themeName.equals("Africa")) {
setTheme(R.style.AppTheme);
} else if (themeName.equals("Colorful Beach")) {
//Toast.makeText(this, "set theme", Toast.LENGTH_SHORT).show();
setTheme(R.style.beach);
} else if (themeName.equals("Abstract")) {
//Toast.makeText(this, "set theme", Toast.LENGTH_SHORT).show();
setTheme(R.style.abstract2);
} else if (themeName.equals("Default")) {
setTheme(R.style.defaulttheme);
}
Please note that you have to put the code before setcontentview..

Android: How to set static value before onCreate is called

I want to have an "option" set before the Activity is created or at least before it starts. If there is a way to do this via the AndroidManifest? Consider this example where we have a global config class that is used in onCreate to instantiate an object (not fully OO for brevity)
public class Global {
public static boolean visible = false;
}
public class MyActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// here is where we want the most up-to-date value of visible
MyObject obj = new MyObject(Global.visible);
}
}
Obviously in this case "visible" would be "false". If this were some sort of API library, we would like to provide the option for users to set "visible" to "true".
Update 1
The objective is to have the global class in a pre-compiled library and have its value set by a developer utilizing the library. I am looking for easiest way for the developer to do this when they create their application; I think the manifest is the probably the way to go but I don't know how to inject the value for "visible" via the xml. The answers below using preferences are good but only cover the users point-of-view.
Update 2
IMHO using resources works best here.
<bool name="visible">true</bool>
public class MyActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// here is where we want the most up-to-date value of visible
Resource res = getResource();
MyObject obj = new MyObject(res.getBoolean(R.bool.visible));
}
}
I think using SharedPreferences would do what you are looking for, using Global.visible as the default value. Then if the user changes it to true, it will use that value.
boolean makeVisible = PreferenceManager.getDefaultSharedPreferences(this).getBoolean(
"MyVisiblePreference",
Global.visible);
MyObject obj = new MyObject(makeVisible);
To allow the preference to be updatable without re-compiling or setting (through a Preferences activity), you can load the default preference from resources:
<bool name="MyVisiblePreference">true</bool>
And reference it similarly with:
boolean makeVisible = PreferenceManager.getDefaultSharedPreferences(this).getBoolean(
"MyVisiblePreference",
getResources().getBoolean(R.bool.MyVisiblePreference));
If the developer does not set the preference to false, it will default to true (based upon the resources value).
For simple objects you can create them like this: (Based off of your code example)
public static boolean visible = false;
public class MyActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// here is where we want the most up-to-date value of visible
MyObject obj = new MyObject(Global.visible);
}
}
For a more complex object you can initialize it with a static initializer like this:
public static boolean visible;
static {
visible = false;
}
public class MyActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// here is where we want the most up-to-date value of visible
MyObject obj = new MyObject(Global.visible);
}
}
You can subclass android.app.Application, this class has method onCreate that you can override. Your subclass have to be defined in AndroidManifest.xml in <application name="YourApplication">. onCreate of application is called before all other components in your application are created (before any Activity or Service).

How to change current Theme at runtime in Android [duplicate]

This question already has answers here:
Implementing user choice of theme
(4 answers)
Closed 5 years ago.
I've created a PreferenceActivity that allows the user to choose the theme he wants to apply to the entire application.
When the user selects a theme, this code is executed:
if (...) {
getApplication().setTheme(R.style.BlackTheme);
} else {
getApplication().setTheme(R.style.LightTheme);
}
But, even though I've checked with the debugger that the code is being executed, I can't see any change in the user interface.
Themes are defined in res/values/styles.xml, and Eclipse does not show any error.
<resources>
<style name="LightTheme" parent="#android:style/Theme.Light">
</style>
<style name="BlackTheme" parent="#android:style/Theme.Black">
</style>
</resources>
Any idea about what could be happening and how to fix it?
Should I call setTheme at any special point in the code? My application consists of several Activities if that helps.
I would like to see the method too, where you set once for all your activities. But as far I know you have to set in each activity before showing any views.
For reference check this:
http://www.anddev.org/applying_a_theme_to_your_application-t817.html
Edit (copied from that forum):
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Call setTheme before creation of any(!) View.
setTheme(android.R.style.Theme_Dark);
// ...
setContentView(R.layout.main);
}
Edit
If you call setTheme after super.onCreate(savedInstanceState); your activity recreated but if you call setTheme before super.onCreate(savedInstanceState); your theme will set and activity
does not recreate anymore
protected void onCreate(Bundle savedInstanceState) {
setTheme(android.R.style.Theme_Dark);
super.onCreate(savedInstanceState);
// ...
setContentView(R.layout.main);
}
If you want to change theme of an already existing activity, call recreate() after setTheme().
Note: don't call recreate if you change theme in onCreate(), to avoid infinite loop.
recreate() (as mentioned by TPReal) will only restart current activity, but the previous activities will still be in back stack and theme will not be applied to them.
So, another solution for this problem is to recreate the task stack completely, like this:
TaskStackBuilder.create(getActivity())
.addNextIntent(new Intent(getActivity(), MainActivity.class))
.addNextIntent(getActivity().getIntent())
.startActivities();
EDIT:
Just put the code above after you perform changing of theme on the UI or somewhere else. All your activities should have method setTheme() called before onCreate(), probably in some parent activity. It is also a normal approach to store the theme chosen in SharedPreferences, read it and then set using setTheme() method.
i got the same problem but i found the solution.
public class EditTextSmartPhoneActivity extends Activity implements DialogInterface.OnClickListener
{
public final static int CREATE_DIALOG = -1;
public final static int THEME_HOLO_LIGHT = 0;
public final static int THEME_BLACK = 1;
int position;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
position = getIntent().getIntExtra("position", -1);
switch(position)
{
case CREATE_DIALOG:
createDialog();
break;
case THEME_HOLO_LIGHT:
setTheme(android.R.style.Theme_Holo_Light);
break;
case THEME_BLACK:
setTheme(android.R.style.Theme_Black);
break;
default:
}
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
private void createDialog()
{
/** Options for user to select*/
String choose[] = {"Theme_Holo_Light","Theme_Black"};
AlertDialog.Builder b = new AlertDialog.Builder(this);
/** Setting a title for the window */
b.setTitle("Choose your Application Theme");
/** Setting items to the alert dialog */
b.setSingleChoiceItems(choose, 0, null);
/** Setting a positive button and its listener */
b.setPositiveButton("OK",this);
/** Setting a positive button and its listener */
b.setNegativeButton("Cancel", null);
/** Creating the alert dialog window using the builder class */
AlertDialog d = b.create();
/** show dialog*/
d.show();
}
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
AlertDialog alert = (AlertDialog)dialog;
int position = alert.getListView().getCheckedItemPosition();
finish();
Intent intent = new Intent(this, EditTextSmartPhoneActivity.class);
intent.putExtra("position", position);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
We have to set theme before calling 'super.onCreate()' and 'setContentView()' method.
Check out this link for applying new theme to whole application at runtime.
I had a similar problem and I solved in this way..
#Override
public void onCreate(Bundle savedInstanceState) {
if (getIntent().hasExtra("bundle") && savedInstanceState==null){
savedInstanceState = getIntent().getExtras().getBundle("bundle");
}
//add code for theme
switch(theme)
{
case LIGHT:
setTheme(R.style.LightTheme);
break;
case BLACK:
setTheme(R.style.BlackTheme);
break;
default:
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//code
}
this code is for recreate the Activity saving Bundle and changing the theme. You have to write your own onSaveInstanceState(Bundle outState); From API-11 you can use the method recreate() instead
Bundle temp_bundle = new Bundle();
onSaveInstanceState(temp_bundle);
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("bundle", temp_bundle);
startActivity(intent);
finish();
Instead of
getApplication().setTheme(R.style.BlackTheme);
use
setTheme(R.style.BlackTheme);
My code: in onCreate() method:
super.onCreate(savedInstanceState);
if(someExpression) {
setTheme(R.style.OneTheme);
} else {
setTheme(R.style.AnotherTheme);
}
setContentView(R.layout.activity_some_layout);
Somewhere (for example, on a button click):
YourActivity.this.recreate();
You have to recreate activity, otherwise - change won't happen
This is what i have created for Material Design. May it will helpful you.
Have a look for MultipleThemeMaterialDesign
I know that i am late but i would like to post a solution here:
Check the full source code here.
This is the code i used when changing theme using preferences..
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(this);
String themeName = pref.getString("prefSyncFrequency3", "Theme1");
if (themeName.equals("Africa")) {
setTheme(R.style.AppTheme);
} else if (themeName.equals("Colorful Beach")) {
//Toast.makeText(this, "set theme", Toast.LENGTH_SHORT).show();
setTheme(R.style.beach);
} else if (themeName.equals("Abstract")) {
//Toast.makeText(this, "set theme", Toast.LENGTH_SHORT).show();
setTheme(R.style.abstract2);
} else if (themeName.equals("Default")) {
setTheme(R.style.defaulttheme);
}
This way work for me:
#Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(GApplication.getInstance().getTheme());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Then you want to change a new theme:
GApplication.getInstance().setTheme(R.style.LightTheme);
recreate();
You can finish the Acivity and recreate it afterwards in this way your activity will be created again and all the views will be created with the new theme.
Call SetContentView(Resource.Layout.Main) after setTheme().
This had no effect for me:
public void changeTheme(int newTheme) {
setTheme(newTheme);
recreate();
}
But this worked:
int theme = R.style.default;
protected void onCreate(Bundle savedInstanceState) {
setTheme(this.theme);
super.onCreate(savedInstanceState);
}
public void changeTheme(int newTheme) {
this.theme = newTheme;
recreate();
}

Categories

Resources