为什么当我尝试设置ActionBar.CustomView.SetBackgroundColor(Color.White);应用程序崩溃了吗?

时间:2019-09-12 06:46:54

标签: xamarin xamarin.forms xamarin.android

为什么当我尝试设置ActionBar.CustomView.SetBackgroundColor (Color.White);时应用程序崩溃?

我尝试通过ResourceDictionary通过样式,toolbar.axml安装ToolbarItems背景,但是这些方法都不适合我-我认为是因为我太笨了。

现在这个选项对我来说是最简单的,因为只有一行代码,但是可以看到冲突的地方是来自style或toolbar.axml或其他东西。 ActionBar.CustomView.SetBackgroundColor (Color.White);

我的app.xaml.cs

using System;
using System.IO;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using MyApp1.Services;
using MyApp1.Views;

namespace MyApp1
{
    public partial class App : Application
    {

        static Data.TodoItemDatabase database;
        public App()
        {
            InitializeComponent();
            MainPage = new AppShell();

        }

        protected override void OnStart()
        {
        // Handle when your app start
        }

        protected override void OnSleep()
        {
            // Handle when your app sleeps
        }

        protected override void OnResume()
        {
            // Handle when your app resumes
        }

        public static Data.TodoItemDatabase Database
        {
            get
            {
                if (database == null)
                {
                    database = new Data.TodoItemDatabase(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "TodoSQLite.db3"));
                }
                return database;
            }
        }

        public int ResumeAtTodoId { get; set; }
    }
}

1 个答案:

答案 0 :(得分:0)

解决方案1:

您可以在Forms中设置TitleView的样式。您可以创建基础Navigation Page并设置TitleView的样式

<NavigationPage.TitleView>

    <StackLayout Orientation="Horizontal" BackgroundColor="White" >
       //...
    </StackLayout>
</NavigationPage.TitleView>

解决方案2

您可以尝试创建一个自定义渲染器,并将其设置为应用中所有页面的基类。在此自定义渲染器中,您可以尝试在CustomTitleView中设置所需的背景颜色和其他样式。

[assembly: ExportRenderer(typeof(Page), typeof(AndroidNavigationPageRenderer )]
public class AndroidNavigationPageRenderer : PageRenderer
{
    private CustomTitleView _titleView;
    public NavigationSearchRenderer(Context context) : base(context)
    {

    }
    protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
    {
        base.OnElementChanged(e);


        var activity = this.Context as FormsAppCompatActivity;
        if (activity == null)
            return;

        var toolbar = activity.FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
        _titleView= new TitleView(Context);
        toolbar.AddView(_titleView);
    }

}