J. Joe
J. Joe

Reputation: 381

How to set actionBar in fragment on Xamarin Android?

I am trying to change the color and image icon on an actionBar

I have tried to use OnAttach but it is not working.

Any help would be much appreciated.

You manipulate action bar only from activity. You can do that in fragment in OnAttach method to make sure you have the reference to the activity.

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);
}

Upvotes: 2

Views: 1541

Answers (1)

Iain Smith
Iain Smith

Reputation: 9703

After testing for abit I could only get the ActionBar in OnActivityCreated in the fragment class:

    public override void OnActivityCreated (Bundle savedInstanceState) {
        base.OnActivityCreated (savedInstanceState);
        Activity activity = this.Activity;
        ActionBar actionBar = activity.ActionBar;
        var colorDrawable = new ColorDrawable(Color.Coral);
        activity.ActionBar.SetBackgroundDrawable(colorDrawable);

        var titleId = activity.Resources.GetIdentifier("action_bar_title", "id", "android");
        var abTitle = activity.FindViewById<TextView>(titleId);
        abTitle.SetTextColor(Color.Black);
    }

Hope this helps.

Upvotes: 1

Related Questions