I am not able to preserve the font for my application label on screen orientation change. Currently I am setting the font using the below code in the onCreate method of SherlockFragmentActivity.
titleId = Resources.getSystem().getIdentifier("action_bar_title", "id", "android");
if(titleId == 0)
titleId = com.actionbarsherlock.R.id.abs__action_bar_title;
mAppName = (TextView) findViewById(titleId);
Typeface face = Typeface.createFromAsset(getAssets(), "fonts/handsean.ttf");
mAppName.setTypeface(face);
On Orientation change the font reverts back to the default. I tried preserving state using manifest.xml but it didnot help. it preserves everything except the label font. Can someone suggest how this can be done ?
Thanks for stopping by and reading this post.
Did you tried setting android:configChanges="orientation" and handling the orientation change with onConfigurationChanged()?
edit: also explained here why it's not functioning.
**Yes we can do this.
Override onConfigurationChanged
set the action bar title inside a handler with a delay of 200.**
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//your code to set the action bar title
setActionBarTitle(title);
}
}, 200);
}
Related
Below code makes the Title bar to go red and Roboto-Regular font, code work properly but when orientation changes then Title will go to default properties, White color and default font.
if i remove config changes in "activity" of manifest then onCreate would be called and font would be Red even after orientation change but i need to have config changes listener.
#Override
protected void onCreate(Bundle savedInstanceState) {
....
Typeface Roboto_Regular = Typeface.createFromAsset(getAssets(),"fonts/Roboto-Regular.ttf");
int titleId = getResources().getIdentifier("action_bar_title", "id","android");
TextView title = (TextView) findViewById(titleId);
title.setTypeface(Roboto_Regular);
title.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Typeface Roboto_Regular = Typeface.createFromAsset(getAssets(),"fonts/Roboto-Regular.ttf");
int titleId = getResources().getIdentifier("action_bar_title", "id","android");
TextView menuTitle = (TextView) findViewById(titleId);
menuTitle.setTypeface(Roboto_Regular);
menuTitle.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
invalidateOptionsMenu();
}
And in manifest
<activity
android:name="com.example.fontexperiment.MainActivity"
android:configChanges="orientation|screenSize"
android:label="#string/app_name" >
------------- updated with more info
android source code
if we read above link, it can be found that android:id="#+id/action_bar_title" is what android has in layout file for title.
I checked in layout-land, there is not separate layout used for case of landscape. So the id of action bar title is same.
in my code i do get a null exception when i do
getResources().getIdentifier("action_bar_title", "id","android")
so the action bar title is proper, but the effect is not happening.
Does onConfigurationChanged() gets called after at end or very beginning? if at beginning then android might be setting title to defaults.
If you need to maintain the same action bar title color on orientation change , I would suggest to create a Custom Theme with your own text color and set to the Activity in manifest.
Check this answer on Changing ActionBar Title Text Color
I am changing the colour of action bar using the following code.
actionBar= getSupportActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(backgroundColor));
This works perfectly fine in onCreate() method(i.e when my activity starts).
But when I am using the same code in Android 4.1 to change color of action bar in onClick() method(i.e when user clicks say a button) then it changes the color of action bar to 'white' ONLY whatsoever be the value of backgroundColor.
In Android 2.3 it works perfectly fine in both cases, whether called from onCreate or onClick().
It seems to be dead end for me.
It seems like for Android 4.0 up to Android 4.1 (4.2 is ok) you cannot change the action bar background once the activity has started.
So I guess a solution in those cases is to restart the activity with a different background color.
Not very elegant but thats the best I can come up with.
Something like this perhaps:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.btn);
if (getIntent().hasExtra("color")) {
getSupportActionBar().setBackgroundDrawable(
new ColorDrawable(getIntent().getIntExtra("color", 0)));
}
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent it = getIntent();
it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
it.putExtra("color", Color.BLUE);
startActivity(it);
}
});
}
A workaround I used to solve this problem was to maintain a reference to the ColorDrawable that was used to set the background initially. Then, to change its colour, modify the colour of the Drawable, and then tell the activity to invalidate its options, which causes the ActionBar to be redrawn. Here's my code to set the action bar color:
ColorDrawable sBackgroundDrawable;
...
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
protected void setActionBarColor(int color){
if(getSherlockActivity() != null && !mCallback.isNavDrawerShowing()){
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH && Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN){
if(sBackgroundDrawable == null){
sBackgroundDrawable = new ColorDrawable(color);
getSherlockActivity().getSupportActionBar().setBackgroundDrawable(sBackgroundDrawable);
}else{
sBackgroundDrawable.setColor(color);
getSherlockActivity().invalidateOptionsMenu();
}
}else{
getSherlockActivity().getSupportActionBar().setBackgroundDrawable(new ColorDrawable(color));
}
}
}
Based off of what steve_the_kid mentioned I was able to solve this by saving the color drawable.
ColorDrawable actionBarBackground = new ColorDrawable();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setBackgroundDrawable(actionBarBackground());
actionBarBackground.setColor(someColor);
}
void onSomethingClick() {
actionBarBackground.setColor(someOtherColor);
}
Sorry for such a late reply,But to help others I am replying to this question after so long.
Just set the Title of the action bar or make change in the icons or menu along with changing the colorDrawables.A simple change will recreate the action bar with new color.Even if you need same title or icon every time set same title or same icon.
I hope this will help others
I'm dynamically setting the Background color and text color of a textview component in my app, using a single options menu button "toggle color"
The problem is, as soon as the orientation changes the textview "forgets" what colors it was supposed to use...so it uses default and not those that were set by the options menu.
Here's the original function of the options menu option :
#Override
public boolean onOptionsItemSelected(MenuItem item) {
TextView textView = (TextView) findViewById(R.id.xxtt);
if (Cflag) {
textView.setBackgroundColor(Color.parseColor("#ffffff"));
textView.setTextColor(Color.parseColor("#000000"));
Cflag= false;
} else {
textView.setBackgroundColor(Color.parseColor("#000000"));
textView.setTextColor(Color.parseColor("#ffffff"));
Cflag= true;
}
return super.onOptionsItemSelected(item);
}
^Cflag is "global" boolean, depending on whether true/false the function sets the textviews color. (If it's black on white, it sets it to white text on black background...and vice-versa)
After doing a little research, Here are the extra functions I modified :
Since on orientation change, the app pauses and resumes, I modified onResume to independently change the color according to the variable Cflag.
And also the OnCofigChange, to update the colors if and when the orientation changes. I've tried using both these functions , and I've tried using them one at a time. Nothing helped.
#Override
protected void onResume() {
TextView textView = (TextView) findViewById(R.id.xxtt);
if (Cflag) {
textView.setBackgroundColor(Color.parseColor("#ffffff"));
textView.setTextColor(Color.parseColor("#000000"));
} else {
textView.setBackgroundColor(Color.parseColor("#000000"));
textView.setTextColor(Color.parseColor("#ffffff"));
}
super.onResume();
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
TextView textView = (TextView) findViewById(R.id.xxtt);
if (Cflag) {
textView.setBackgroundColor(Color.parseColor("#ffffff"));
textView.setTextColor(Color.parseColor("#000000"));
} else {
textView.setBackgroundColor(Color.parseColor("#000000"));
textView.setTextColor(Color.parseColor("#ffffff"));
}
}
I don't want to unnecessarily use a SharedPreferences object.
I reckon it's a matter of logic only,
If it's black text on white background(default) .... Press the option menu's option, It toggles to white text on black background .... Cflag variable is also toggled.
Now Cflag is constant, we just have to set the text color again according to Cflag.
But I can't get it to work: I change the settings in one orientation, and on switching orientation it goes back to default state(The one I defined in XML, black text on white background..)
What's wrong?
Thank you !
Save them in bundle
#Override
protected void onSaveInstanceState (Bundle outState) {
outState.putBoolean("CFLAG",CFlag);
}
and it will be restored in Activity onCreate.
#Override
protected void onCreate (Bundle savedInstanceState) {
CFlag = savedInstanceState.getBoolean("CFLAG");
}
I'm using an activity with a webview and to keep it from refreshing whenever the device is rotated, I have android:configChanges="orientation|screenSize" in AndroidManifest.xml. The problem is that whenever the device is rotated, the changes I have made to the status bar dissapear. Does anyone know how to keep the webview from refreshing whenever rotated AND keep the changes I've made in the status bar?
This is the method that I use to make the changes to the statusbar
public static void changeActionBarFont(Activity activity) {
Typeface slab = Typeface.createFromAsset(activity.getAssets(),
"RobotoSlab.ttf");
int actionBarTitle = Resources.getSystem().getIdentifier(
"action_bar_title", "id", "android");
int actionBarSubTitle = Resources.getSystem().getIdentifier(
"action_bar_subtitle", "id", "android");
if (0 == actionBarTitle & 0 == actionBarSubTitle) {
actionBarTitle = com.actionbarsherlock.R.id.abs__action_bar_title;
actionBarSubTitle = com.actionbarsherlock.R.id.abs__action_bar_subtitle;
}
TextView title = (TextView) activity.getWindow().findViewById(
actionBarTitle);
TextView subtitle = (TextView) activity.getWindow().findViewById(
actionBarSubTitle);
if (title != null | subtitle != null) {
title.setTypeface(slab);
subtitle.setTypeface(slab);
subtitle.setTextColor(Color.parseColor("#FFFFFFFF"));
}
}
Edit: Removeing the configChanges from the AndroidManifest does in fact fix the problem with the ActionBar, but I need them to keep the webview from reloading whenever the device is rotated. Anyone have any ideas as to how I can keep them both?
It may not be what you want to hear right now, but it is better to try to recreate the layout in the new orientation, rather than just preventing the orientation change.
In your onCreate check whether there is a saved instance (as a result of the orientation change) e.g.
if (savedInstanceState == null) {
//recreate the current state
}
else {
//normal start
}
You might need to retain some values (either in Shared Prefs or onSavedInstanceState).
This approach is more difficult than locking the orientation, but it is a better approach in the long run and is well worth the investment (extra effort).
I have create dialog box which will be displayed first when i start application (which is coded in onCreate method ) and then question and answer will be displayed on textview
so to solve problem of orientation (so dialog box again not displayed when orientation change) i have used Manifest with:
android:configChanges="keyboardHidden|orientation"
I have res/layout-land, res/layout-port
but to change only COLOR of background
I have used onConfigurationChanged in my Activity (it get's called on rotation).
so now when orientation change the dialog box will not appear again and background is redrawn but the question and answer which is initialized on onCreate() will not display
so how to maintain
Using android:configChanges="keyboardHidden|orientation" means that your activity handles a configuration change itself, and the system will not change the layout.. take a lokk at http://developer.android.com/guide/topics/resources/runtime-changes.html
To reset the text view, in case of not using android:configChanges="keyboardHidden|orientation":
#Override
public Object onRetainNonConfigurationInstance() {
final MyDataObject data = collectMyLoadedData();
//here get the text from the text view, and any other info
return data;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final MyDataObject data = (MyDataObject) getLastNonConfigurationInstance();
if (data != null) {
//get the text and set it in the text view
}
}
When you change the orientation of the devide, android continue the execution without calling onCreate again, but if you put the code in onResume, this code will executed again.
In OnCreate add for your main layout as
LinearLayout lv=(LinearLayout)findViewById(R.id.mainlayout);
lv.setBackgroundColor(android.R.color.black); // for default potrait or landscape view and after that add this in that activity
#Override
public void onConfigurationChanged(Configuration newConfig) {
Configuration c = getResources().getConfiguration();
if(c.orientation == Configuration.ORIENTATION_PORTRAIT ) {
// portrait
lv.setBackgroundColor(android.R.color.black);
} else if(c.orientation == Configuration.ORIENTATION_LANDSCAPE ){
// landscape
lv.setBackgroundColor(android.R.color.white);
}
}
and also add this in menifest in your activity defined
android:configChanges="keyboardHidden|orientation"
Did you use onSaveInstanceState to save the data and onRestoreInstanceState for retriving the data?
If you have done this then you can display the same dialog box in onRestoreInstanceState.
Well I have a question for you. How did you kept the background color unchanged when changing the orientations? And what to do if the color is unknown or a random color?