I want to change the color of my action bar and status bar programmatically only on one activity, depending it's state, green for go and red for stop. I want to keep the system wide theme of orange and only have the red or green depending on the outcome of whats inside the activity, with an if Statement.
How could it be possible to do that?
Asked
Active
Viewed 1.6k times
3

Dumbo
- 1,630
- 18
- 33
-
I also need to change the colour of my status bar – Feb 22 '18 at 14:19
2 Answers
5
if I understand correctly you want to change from java code .. When you call an if try to use this method:
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
changeColor(R.color.red);
}
public void changeColor(int resourseColor) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(ContextCompat.getColor(getApplicationContext(), resourseColor));
}
ActionBar bar = getSupportActionBar();
bar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(resourseColor)));
}
}

Mattia Ferigutti
- 2,608
- 1
- 18
- 22
-
-
`R.color.red` is defined color name in *`res/values/colors.xml`*. Example: `
#770000 ` @zarrexx – Dumbo Feb 22 '18 at 14:52 -
-
-
-
-
@zarrexx if you want to use class variable with "#FF0000" value. You can use `Color.parseColor(stringVariable);` instead of `ContextCompat.getColor(getApplicationContext(), resourseColor)` and `getResources().getColor(resourseColor)`. – Dumbo Feb 22 '18 at 15:06
-
Could you show how I could adapt the `changeColor` method to use `changeColor(Color.parseColor("#00FF00"));` – Feb 22 '18 at 15:09
-
@zarrexx look there: https://www.dropbox.com/s/4w2kqnaak8149wx/answer_.txt?dl=0 – Dumbo Feb 22 '18 at 15:14
-
4
You can do it by defining the custom theme for activity. First you need to create styles.xml
file in res/values/
path.
styles.xml
<resources>
<style name="MyCustomTheme" parent="Theme.AppCompat.Light">
<item name="android:statusBarColor">@color/color_primary</item>
<item name="android:actionBarStyle">@style/MyActionBar</item>
</style>
<style name="MyActionBar" parent="@android:style/Widget.Holo.Light.ActionBar">
<item name="android:background">@color/color_primary</item>
</style>
</resources>
Then in your AndroidManifest.xml
write:
<activity
android:name=".MyActivity"
android:theme="@style/MyCustomTheme"/>
Or in your activity:
setTheme(android.R.style.MyCustomTheme);

Dumbo
- 1,630
- 18
- 33
-
-
You can use `setTheme(android.R.style.MyCustomTheme)` method after your `if()` statement. @zarrexx – Dumbo Feb 22 '18 at 14:33