问题
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
回答1:
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);
}
回答2:
In a Fragment, the ActionBar view is usually handled through overriding the:
public override void OnCreateOptionsMenu(IMenu menu, MenuInflater inflater)
callback method; after making sure you have called SetHasOptionsMenu(true); in OnCreate().
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:
public override void OnCreateOptionsMenu(IMenu menu, MenuInflater inflater)
{
//Stops the menu being reinflated on configuration changes
if(!menu.HasVisibleItems)
inflater.Inflate(Resource.Menu.MenuLayout, menu);
var myMenuItem = menu.FindItem(Resource.Id.MyMenuItem);
//Do stuff with your menu items
}
回答3:
You can access the Activity from the Fragment by using Activity property at any time, that will return the Activity associated with the Fragment.
来源:https://stackoverflow.com/questions/23993006/change-actionbar-color-in-a-fragment