在片段更改动作条的颜色片段、颜色、动作

2023-09-12 02:55:40 作者:赌约

在Xamarin,我怎么能修改动作条背景颜色和文字颜色在片段

In Xamarin, how can I change the ActionBar background color and text color in a Fragment?

下面是code,在一个活动的作品

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

如果我有相同的code,对于同一项目,在片段,我得到以下错误:

If I have the same code, for the same project, in a Fragment, I get the following error:

这是对象引用是所必需的非静态字段,方法,或   属性   Android.App.ActionBar.SetBackgroundDrawable(Android.Graphics.Drawables.Drawable)

An object reference is required for the non-static field, method, or property 'Android.App.ActionBar.SetBackgroundDrawable(Android.Graphics.Drawables.Drawable)'

在这行code:

ActionBar.SetBackgroundDrawable(colorDrawable);

如果我注释掉code以上的线,我得到这个错误:

And if I comment out the above line of code, I get this error:

System.NullReferenceException:对象未设置为一个实例   一个对象的

System.NullReferenceException: Object reference not set to an instance of an object

在这行code:

abTitle.SetTextColor (Color.Black);

此外,我把这个code。在 OnCreateView 的功能。

如何在code需要改变,使其工作在片段,而不是在活动

How does the code need to be changed so that it will work in a Fragment, rather than in an Activity?

在此先感谢

推荐答案

我发现,要做到这一点,我需要从活动的操纵操作栏

I have found that to do this I need to manipulate the action bar from the activity

下面是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);
}