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:
public override void OnAttach(Activity activity)
{
base.OnAttach(activity);
var colorDrawable = new ColorDrawable(Color.White);
activity.ActionBar.SetBackgroundDrawable(colorDrawable);
var titleId = activity.Resources.GetIdentifier("action_bar_title", "id", "android");
var abTitle = activity.FindViewById<TextView>(titleId);
abTitle.SetTextColor(Color.Black);
}