Change ActionBar color in a Fragment

2019-05-30 16:04发布

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

3条回答
时光不老,我们不散
2楼-- · 2019-05-30 16:47

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);
}
查看更多
ゆ 、 Hurt°
3楼-- · 2019-05-30 16:51

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
}
查看更多
Deceive 欺骗
4楼-- · 2019-05-30 16:52

You can access the Activity from the Fragment by using Activity property at any time, that will return the Activity associated with the Fragment.

查看更多
登录 后发表回答