Change Action Bar - java

I would like to create a new activity that includes more buttons. Each button represents a color. How can I change the action bar (and save) if I click on a button that represents a color (red for example)?
I did something that changes the color of the action bar, but if I go on the home page, the color will change again. Do I need to serialize something? Thanks!
pink.setOnClickListener(new View.OnClickListener(){
public void onClick(View view){
getSupportActionBar().setTitle("Pink");
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.colorPink)));
if(Build.VERSION.SDK_INT >=Build.VERSION_CODES.LOLLIPOP){
Window window =getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(getResources().getColor(R.color.colorAccent));
}
}
});
Button xml.
<Button android:id="#+id/button_pink" android:layout_width="296dp"
android:layout_height="49dp" android:layout_marginTop="26dp"
android:background="#color/colorPink" android:text="pink"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent" />
</android.support.constraint.ConstraintLayout>

Read the documentation first. As written in the documentation.
<resources>
<style name="MyTheme" parent="#android:style/Theme.Holo.Light">
<item name="android:actionBarStyle">#style/MyActionBar</item>
</style>
<style name="MyActionBar" parent="#android:style/Widget.Holo.Light.ActionBar">
<item name="android:background">ANY_HEX_COLOR_CODE</item>
</style>
</resources>
And, set "MyTheme" as theme for application / activity.

This is happening because when you restart your activity then according to activity life cycle onReStart() and then onStart() is called so the action bar color becomes default. As in your code you are setting action bar color on a click event.
Possible solution is that in your button click event you can save the color value in a shared preference and then use that shared preference in your onCreate() with the color changing code. This will make your app to set the color that is saved previously.
Android Lifecycle
Shared Preference
onCreate(){
sharedPreferences = getSharedPreferences("NAME", Context.MODE_PRIVATE);
int color = sharedPreferences.getInt("color", "DEFAULT_COLOR");
String title = sharedPreferences.getString("text", "DEFAULT_TEXT");
getSupportActionBar().setTitle(title);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(USE_THE_COLOR_VALUE_HERE)));//
if(Build.VERSION.SDK_INT >=Build.VERSION_CODES.LOLLIPOP){
Window window =getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(getResources().getColor(R.color.colorAccent));
}
}
And in your button click store the color and title
onclick(){
SharedPreferences.Editor editor = sharedPreferences.edit();
editor = sharedPreferences.edit();
editor.putString("text","YOUR_TEXT");
editor.putInt("color","YOUR_COLOR");
editor.commit();
}
If you still face any problem in saving your color in shared preference you can see
How to store color value in SharedMemory?

onClick button color changer
int color = R.color.colorPink;
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(color)));
And save onClick
SharedPreferences preferences = getSharedPreferences ("prefKey", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt ("colorValue", color);
editor.apply ();
onCreate
SharedPreferences preferences = getSharedPreferences ("prefKey", Mode_Private);
int color = preferences.getInt ("colorValue", 0);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(color)));

Related

Trying to save color from AmbilWarnaDialog with SharedPreferences it is not getting the color

I have a dialog for ColorPicker which is added at build.gradle.
The dialog it is AmbilWarnaDialog.
I am able to change the color but the problem it is when I exit the app and again I open the color is the colorPrimary it is not getting the color from SharedPreferences.
I am able to save a color at the SharedPreferences but then it is not getting the color from there.
Below is my code.
MainActivity.class
SharedPreferences sharedpreferences = getSharedPreferences(Change_Color, Context.MODE_PRIVATE);
int backcolorValue = sharedpreferences.getInt("back_color_code", 1);
if (backcolorValue != 1) {
Log.d("TAG", "onCreate: " + "e pera");
changeHeader.setBackgroundColor(backcolorValue);
getWindow().setStatusBarColor(backcolorValue);
} else {
changeHeader.setBackgroundColor(mDefaultColor);
}
public void openColorPicker() {
AmbilWarnaDialog colorPicker = new AmbilWarnaDialog(this, mDefaultColor, new AmbilWarnaDialog.OnAmbilWarnaListener() {
#Override
public void onCancel(AmbilWarnaDialog dialog) {
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void onOk(AmbilWarnaDialog dialog, int color) {
changeHeader.setBackgroundColor(color);
getWindow().setStatusBarColor(color);
SharedPreferences sharedpreferences = getSharedPreferences(Change_Color, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("back_color_code", color);
editor.apply();
Log.d("TAG", "onOk: " + color);
}
});
colorPicker.show();
}
activity_main.XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
style="#style/ActivityMain">
<RelativeLayout
android:id="#+id/relLayoutTitle"
style="#style/RelativeLayoutTitleSearch">
</RelativeLayout>
</RelativeLayout/
styles.xml
<style name="RelativeLayoutTitleSearch">
<item name="android:background">#color/blue_title</item>
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">#dimen/title_height</item>
<item name="android:adjustViewBounds">true</item>
</style>
The color at the Dialog return a number something like -112332
I have found where was the problem.
I have two times declared the defaultColor and it has take the non modified color.
I just have deleted one of them and it is working.

Set height of Snackbar in Android

I have a Snackbar in need to set its height or set height to wrap content. Is there any way?
Snackbar snack = Snackbar.make(findViewById(R.id.activity_container), "Message", Snackbar.LENGTH_SHORT);
View view = snack.getView();
TextView tv = (TextView) view.findViewById(android.support.design.R.id.snackbar_text);
view.setBackgroundColor(Color.RED);
tv.setTextColor(Color.WHITE);
tv.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
tv.setGravity(Gravity.CENTER_HORIZONTAL);
We are going to provide multiple answers. First a statement or two! You can set the height and width of a Snackbar but it is messy and time consuming period.
One realization about a Snackbar widget is most tutorials do not talk about styling. The opinion is they should be just the size that the widget gives you NOT MY VIEW. So we have noticed that the text size and number of max lines plays a BIG roll is the size of a well styled Snackbar. So design your Snackbar and style away
OK how to implement the mess Suggestion DO NOT DO THIS declare this variable where you would declare any other variable in your Activity
RelativeLayout rl;
Then when you need to increase the size of your RelativeLayout that is in your XML file but is not the root Layout in this case use this code
rl = (RelativeLayout) findViewById(R.id.svRL);
rl.getLayoutParams().height = 1480;
When you get done with this increased size which can mess with the size of other object in the root Layout you might want to set the size of the root Layout back to what it was. In this case the root Layout was set to layout height 615dp we are working with a Nexus 7 Tablet. If you have not noticed this yet here is the MESS part that 1480 is in units of pixels and you need it in dp. I am sure the conversion can be made just do not ask me. So here is the set back line of code
rl.getLayoutParams().height = 1230;
Now for a easy way to design and style two types of Snackbar's one with an Action button and one with out. First you need a CoordinatorLayout in what ever Activity corresponding XML file that looks like this Note it has an id
<android.support.design.widget.CoordinatorLayout
android:id="#+id/coorSB"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" >
<!-- android.support.design.widget.SnackBar -->
<!--stuff you want inside the coordinator ... -->
</android.support.design.widget.CoordinatorLayout>
Now we are ready to do some work in the Activity to design and style after a little advanced string and color set up. Please do not be offended I am being very thorough because you seem to be very new to programming.
<string name="snackbar_text">I Am a NEW SnackBAR TEXT</string>
<string name="snackbar_action">EXIT</string>
<string name="second_text">Second Text</string>
<string name="csb_text">I am the Custom Guy</string>
<string name="csb_action">EXIT</string>
<string name="the_text">Password must have one Numeric Value\n"
"One Upper & Lower Case Letters\n"
"One Special Character $ # ! % * ? &\n"
"NO Spaces in the PASSWORD"</string>
Now for the Rainbow many ways to manage Color this is my mine.
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303f9f</color>
<color name="colorAccent">#FF4081</color>
<color name="color_Black">#000000</color>
<color name="color_White">#FFFFFF</color>
<color name="color_darkGray">#606060</color>
<color name="color_lightGray">#C0C0C0</color>
<color name="color_super_lightGray">#E0E0E0</color>
<color name="color_Red">#FF0000</color>
<color name="color_Yellow">#FFFF66</color>
<color name="color_deepBlue">#0000ff</color>
<color name="color_lightBlue">#3333FF</color>
<color name="color_Purple">#9C27B0</color>
<color name="color_Transparent">#android:color/transparent</color>
Done with house keeping in your Activity where you declare variables add this
private CoordinatorLayout myLayout;
Snackbar sb = null;
private CoordinatorLayout noActLayout;
Snackbar sbNoAct = null;
There here is the implementation of both types of Snackbars
public void makeNoAct(View view){
// this is declared on a Button android:onClick="makeNoAct"
noActLayout = (CoordinatorLayout)findViewById(R.id.coorSB);
sbNoAct = Snackbar.make(noActLayout,R.string.the_text,1);// any interger will make it happy
sbNoAct.setDuration(3000);// 3 sec // OR Snackbar.LENGTH_LONG
// matters NOT you are setting duration
View sbView = sbNoAct.getView();
sbView.setBackgroundColor(ContextCompat.getColor(this, R.color.color_Black));
TextView textViewNoAct = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
//set text color
textViewNoAct.setTextColor(ContextCompat.getColor(this,R.color.color_Yellow));
textViewNoAct.setMaxLines(10);
textViewNoAct.setTextSize(24);
//increase max lines of text in snackbar. default is 2.
sbNoAct.show();
int height = sbView.getHeight();
etNewData.setText(String.valueOf(height));
}
public void makeCOOR(View view) {
// this is declared on a Button android:onClick="makeCOOR"
// We were to Lazy to write an OnClickListener
myLayout = (CoordinatorLayout) findViewById(R.id.coorSB);
sb = Snackbar.make(myLayout, R.string.csb_text, Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.csb_action, myOnClickListener)
.setActionTextColor(ContextCompat.getColor(context, R.color.color_Red));
View sbView = sb.getView();
sbView.setBackgroundColor(ContextCompat.getColor(this, R.color.color_White));
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
//set text color
textView.setTextColor(ContextCompat.getColor(this,R.color.color_deepBlue));
textView.setTextSize(30);
//increase max lines of text in snackbar. default is 2.
textView.setMaxLines(10);
// NOTE new View
TextView textAction = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_action);
//set Action text color
textAction.setTextColor(ContextCompat.getColor(this,R.color.color_Red));
textAction.setTextSize(30);
sb.show();
}
View.OnClickListener myOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// OR use and Intent to go somewhere have a nice trip
sb.dismiss();
System.out.println("========= I WAS DISMISSED ===============");
}
};
Enjoy the code and let us know with a comment if this solves your issue.
This is very simple to change the height or width of Snackbar .
Just we need to write 2 , 3 line of code to do this.
Check the below code snippet .
Snackbar snackbar = Snackbar.make(view, "Your message", Snackbar.LENGTH_LONG);
snackbar.setAction("Ok", new View.OnClickListener() {
#Override
public void onClick(View view) {
//your click action.
}
});
Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout)snackbar.getView();
layout.setMinimumHeight(50);//your custom height.
snackbar.show();
final String CR= System.getProperty("line.separator") ;
String snackMsg= "First line" + CR;
snackMsg+="Second line." +CR;
snackMsg+="... more lines." +CR;
final Snackbar snack = Snackbar.make(findViewById(android.R.id.content), snackMsg, Snackbar.LENGTH_INDEFINITE);
snack.setAction("OK", new View.OnClickListener() {
#Override
public void onClick(View v) {
// Respond to the click, such as by undoing the modification that caused
// this message to be displayed
}
});
View view = snack.getView();
TextView tv = (TextView) view.findViewById(android.support.design.R.id.snackbar_text);
// tv.setBackgroundColor(Color.RED);
tv.setLines(12);
FrameLayout.LayoutParams params =(FrameLayout.LayoutParams)view.getLayoutParams();
params.gravity = Gravity.TOP;
//params.height=2000;
params.bottomMargin=10;
view.setLayoutParams(params);
snack.show();
You may also need to set the size for the inner container of a snackbar in order for the text to be aligned/centered vertically. Here is a solution (Kotlin):
Snackbar.make( containerView, msg, duration ).also {
// outer container
it.view.minimumHeight = minHeightPx
// inner container
( it.view as? Snackbar.SnackbarLayout )?.getChildAt( 0 )?.let { innerView ->
innerView.minimumHeight = minHeightPx
}
}.show()
Snackbar snack = Snackbar.make(findViewById(R.id.activity_container), "Message", Snackbar.LENGTH_SHORT);
View view = snack.getView();
TextView tv = (TextView) view.findViewById(android.support.design.R.id.snackbar_text);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)tv.getLayoutParams();
params.height = 80;
tv.setTextColor(Color.WHITE);
tv.setGravity(Gravity.CENTER_HORIZONTAL);
tv.setLayoutParams(params);
snack.show();

SharedPreferences not Automatically Saving?

My preference values aren't saving and everytime I read the SharedPreferences file it returns default values; changes are supposed to be automatically handled by the system when a user makes a choice (like selecting an option in a ListPreference) so I don't know why this isn't happening in my app.
According to google
"When the user changes a setting, the system updates the corresponding value in the SharedPreferences file for you. The only time you should directly interact with the associated SharedPreferences file is when you need to read the value in order to determine your app's behavior based on the user's setting."
Should I be manipulating a SharedPreference.Editor instance in my OnSharedPreferenceChangeListener or is there something else I need to do to make values of user settings persist?
The Problem in Code: As a result of this misunderstanding, my code doesn't persist user settings values (the default value is always chosen when I read the SharedPreference file in my MainActivity's OnCreate). As it is now, the buttons chosen in my Preferences menu View persist upon app restarts, but it seems that choosing an option in this menu doesn't save key values to the SharedPreferences file.
What do I need to do to make the values set by the user in my ListPreference persist?
MainActivity
public class MainActivity extends FragmentActivity {
private static int prefWoodColor; //saved pref variable for OpenGL neck texture
private SharedPreferences settings;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
//Restore preferences
settings = PreferenceManager.getDefaultSharedPreferences(this);
prefWoodColor = Integer.parseInt(settings.getString(this.KEY_PREF_WOOD_TYPE, "Maple"));
...
}
}
Preferences Activity
public class FragmentSettingsMenu extends com.takisoft.fix.support.v7.preference.PreferenceFragmentCompat {
private SharedPreferences.OnSharedPreferenceChangeListener listener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from the XML resource
addPreferencesFromResource(R.xml.preferences);
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (key.equals("pref_wood")) {
Preference woodPref = findPreference(key);
String color = woodPref.getSharedPreferences().getString(key, "Maple");
//Should I be calling edit.apply() logic here?
}
}
};
}
...
}
Preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
android:title="Settings"
<ListPreference
android:key="pref_wood"
android:title="#string/pref_wood"
android:dialogTitle="#string/pref_wood"
android:entries="#array/pref_wood_entries"
android:entryValues="#array/pref_wood_values"
android:defaultValue="#string/pref_wood_default" />
</PreferenceScreen>
Strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">MyApp</string>
<string name="dummy_button">Dummy Button</string>
<string name="dummy_content">DUMMY\nCONTENT</string>
<!--Preference Menu Strings-->
<string name="pref_wood">Wood Style</string>
<string-array name="pref_wood_entries">
<item>"Maple"</item>
<item>"Cedar"</item>
<item>"Oak"</item>
</string-array>
<string-array name="pref_wood_values">
<item >0</item>
<item >1</item>
<item >2</item>
</string-array>
<string name="pref_wood_default">Maple</string>
</resources>
The system saves changes automatically!

Android: Modifying Object's Fields With Its Own Click Listener

I have several radio buttons, each of which has a View.OnClickListener. The whole purpose of those listeners are for me to be able to change the color of the text associated with the RadioButton upon clicking this very RadioButton. My problem is, I'm not sure how to do that.
Here is how I set a listener for each RadioButton:
radioButton.setOnClickListener(badAnswerListener());
Here's the badAnswerListener method:
private View.OnClickListener badAnswerListener(){
return new View.OnClickListener() {
#Override
public void onClick(View arg0) {
//How do I change the radioButton's color?
}
};
}
If radioButton is private member of class :
radioButton.setTextColor(R.color.customcolor);
See this too, it's almost the same question :
Changing Text color of RadioButton if clicked in android
if you are only using radio button clicklistners to change the color of text.Have a look at the better approach.To change the text color when radio button is checked(clicked)
1) Use radio_text_selector.xml as below and put it into res/color folder:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:color="#android:color/red" />
<item android:color="#504f4f" /> <--default case
</selector>
Use the above selector in "android:textColor" attribute like below
<RadioButton
android:id="#+id/radioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/radio_text_selector" />
private View.OnClickListener badAnswerListener(){
return new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Change the clicked radioButton's text to red
((RadioButton) arg0).setTextColor(Color.RED);
}
};
}

Saving changed Activity background colour on button click

I have this code which allows me to change the background colour of my activity and I call this on a button click.
View someView = findViewById(R.id.mainLayout);
View root = someView.getRootView();
root.setBackgroundColor(0xFF00FF00);
How can I save the background colour so that it stays changed whenever the app is restarted.
If you need to persist this setting across multiple starts by the user use SharedPreferences as described here:
http://developer.android.com/training/basics/data-storage/shared-preferences.html
If you only want to keep this setting when re-created by the system because of orientation changes for example, use onSaveInstanceState() and check for a Bundle in onCreate() as described here:
http://developer.android.com/training/basics/activity-lifecycle/recreating.html
Save to SharedPref.
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(KEY, Value);
editor.commit();
Read from SharedPref.
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int i = sharedPref.getInt(KEY, defaultValue);
Set Flag in sharedPreferences by
Editor editor = sharedpreferences.edit();
editor.putString(Flag, "Y");
And while loading the screen in Oncreate check for the flag by
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if (sharedpreferences.contains(Flag))
{
name.setText(sharedpreferences.getString(Flag, ""));
}

Categories

Resources