In Xamarin, how can I change the ActionBar
background color and text color in a Fragment
?
Here is the code that works in an Activity
:
ColorDrawable colorDrawable = new ColorDrawable(Color.White);
ActionBar.SetBackgroundDrawable(colorDrawable);
int titleId = Resources.GetIdentifier("action_bar_title", "id", "android");
TextView abTitle = (TextView) FindViewById(titleId);
abTitle.SetTextColor (Color.Black);
If I have the same code, for the same project, in a Fragment
, I get the following error:
An object reference is required for the non-static field, method, or property 'Android.App.ActionBar.SetBackgroundDrawable(Android.Graphics.Drawables.Drawable)'
At this line of code:
ActionBar.SetBackgroundDrawable(colorDrawable);
And if I comment out the above line of code, I get this error:
System.NullReferenceException: Object reference not set to an instance of an object
At this line of code:
abTitle.SetTextColor (Color.Black);
Also, I am placing this code in the OnCreateView
function.
How does the code need to be changed so that it will work in a Fragment
, rather than in an Activity
?
Thanks in advance
I have found that to do this I need to manipulate the action bar from the activity
Here is the code:
In a
Fragment
, theActionBar
view is usually handled through overriding the:callback method; after making sure you have called
SetHasOptionsMenu(true);
inOnCreate()
.It is possible that you are getting that
NullReferenceException
because OnCreateView() is being called before the ActionBar layout has been inflated.Typically, this is what my method will look like:
You can access the Activity from the Fragment by using Activity property at any time, that will return the Activity associated with the Fragment.