Xamarin.Android: не удается переписать на C # без шаблона XML-проекта — приложение панели навигации

#c# #xamarin #xamarin.android #drawerlayout #android-navigationview

#c# #xamarin #xamarin.android #drawerlayout #android-navigationview

Вопрос:

Я пытаюсь переписать шаблон Xamarin.Проект Android в Microsoft Visual Studio «Приложение панели навигации». без использования XML-разметки для макетов, за исключением констант или даже пунктов меню. Я переписал его, но он не идеален. Боковая панель навигации просто не отображается. Люди, помогите мне, пожалуйста 🙂 Вот ссылка на мой проект: https://drive.google.com/drive/folders/11Q-L-hwIiL4FtdyX0iAYycQDsgTbGuR9?usp=sharing Вот мои визуальные результаты:

 using System;
using System.Xml.Schema;
using Android;
using Android.App;
using Android.Graphics;
using Android.OS;
using Android.Runtime;
using Android.Support.Annotation;
using Android.Support.Design.Widget;
using Android.Support.V4.View;
using Android.Support.V4.Widget;
using Android.Support.V7.App;
using Android.Views;
using Android.Widget;


namespace NavigationMenuTestApp
{
    [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
    public class MainActivity : AppCompatActivity
    {
        DrawerLayout drawer;
        ActionBarDrawerToggle toggle;

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);

            // Create your application here

            #region content_main
            var content_mainLayout = new RelativeLayout(this);
            content_mainLayout.LayoutParameters = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MatchParent, RelativeLayout.LayoutParams.MatchParent);

            TextView tView1 = new TextView(this);
            tView1.Text = "Hello World!";
            var tView1LayParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MatchParent, RelativeLayout.LayoutParams.MatchParent);
            // android:layout_centerInParent = "true"
            tView1.LayoutParameters = tView1LayParams;
            content_mainLayout.AddView(tView1);
            #endregion

            #region nav_header_main
            var nav_header_mainLayout = new LinearLayout(this);
            nav_header_mainLayout.LayoutParameters = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, Resource.Dimension.nav_header_height);
            //nav_header_mainLayout.Background = (Android.Graphics.Drawables.Drawable)Resource.Drawable.side_nav_bar;
            nav_header_mainLayout.SetGravity(GravityFlags.Bottom);
            nav_header_mainLayout.Orientation = Orientation.Vertical;
            nav_header_mainLayout.SetPadding
            (
                Resource.Dimension.activity_horizontal_margin,
                Resource.Dimension.activity_vertical_margin,
                Resource.Dimension.activity_horizontal_margin,
                Resource.Dimension.activity_vertical_margin
            );
            nav_header_mainLayout.ScrollBarStyle = (ScrollbarStyles)Resource.Style.ThemeOverlay_AppCompat_Dark;

            //ImageView imageView = new ImageView((Android.Content.Context)Resource.Mipmap.ic_launcher);
            //imageView.SetPadding(0, Resource.Dimension.nav_header_vertical_spacing, 0, 0);
            //var imageViewLayParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WrapContent, LinearLayout.LayoutParams.WrapContent);
            //imageView.LayoutParameters = imageViewLayParams;

            TextView textView1 = new TextView(this);
            textView1.SetPadding(0, Resource.Dimension.nav_header_vertical_spacing, 0, 0);
            textView1.Text = @"Xamarin.Android";
            textView1.SetTextAppearance(Resource.Style.TextAppearance_AppCompat_Body1);
            //var textView1LayParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.WrapContent);
            //textView1.LayoutParameters = textView1LayParams;

            TextView textView2 = new TextView(this);
            textView2.SetPadding(0, Resource.Dimension.nav_header_vertical_spacing, 0, 0);
            textView2.Text = @"xamarin@microsoft.com";
            textView2.SetTextAppearance(Resource.Style.TextAppearance_AppCompat_Body1);
            //var textView2LayParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WrapContent, LinearLayout.LayoutParams.WrapContent);
            //textView2.LayoutParameters = textView2LayParams;

                //nav_header_mainLayout.AddView(imageView); //...

            // nav_header_mainLayout.AddView(textView1);     
            nav_header_mainLayout.AddView
            (
                textView1,
                ViewGroup.LayoutParams.MatchParent,
                ViewGroup.LayoutParams.WrapContent
            );

            // nav_header_mainLayout.AddView(textView2);
            nav_header_mainLayout.AddView
            (
                textView2,
                ViewGroup.LayoutParams.WrapContent,
                ViewGroup.LayoutParams.WrapContent
            );          
            #endregion

            #region app_bar_main
            var coordinatorLayout = new CoordinatorLayout(this);
            coordinatorLayout.LayoutParameters = new CoordinatorLayout.LayoutParams(CoordinatorLayout.LayoutParams.MatchParent, CoordinatorLayout.LayoutParams.MatchParent);

            var appBarLayout = new AppBarLayout(this);
            appBarLayout.LayoutParameters = new AppBarLayout.LayoutParams(AppBarLayout.LayoutParams.MatchParent, AppBarLayout.LayoutParams.WrapContent);
            //appBarLayout.ScrollBarStyle = (ScrollbarStyles)Resource.Style.AppTheme_AppBarOverlay;

            Android.Support.V7.Widget.Toolbar toolbar = new Android.Support.V7.Widget.Toolbar(this);
            toolbar.LayoutParameters = new Android.Support.V7.Widget.Toolbar.LayoutParams(Android.Support.V7.Widget.Toolbar.LayoutParams.MatchParent, Resource.Attribute.actionBarSize);
            //toolbar.Background = (Android.Graphics.Drawables.Drawable)Resource.Attribute.colorPrimary;
            //toolbar.PopupTheme = Resource.Style.AppTheme_PopupOverlay;

            //<include layout="@layout/content_main" />

            var fab = new FloatingActionButton(this);
            fab.SetForegroundGravity(GravityFlags.Bottom | GravityFlags.End);
           
            // android:layout_margin="@dimen/fab_margin" ...
            //fab.SetCompatElevationResource(Android.Resource.Drawable.IcDialogEmail);

            var fabLayParams = new CoordinatorLayout.LayoutParams(CoordinatorLayout.LayoutParams.WrapContent, CoordinatorLayout.LayoutParams.WrapContent);
            fabLayParams.MarginEnd = Resource.Dimension.fab_margin; //...
            fabLayParams.BottomMargin = Resource.Dimension.fab_margin; //...
            fab.LayoutParameters = fabLayParams;

            appBarLayout.AddView(toolbar);
            coordinatorLayout.AddView(appBarLayout);
            coordinatorLayout.AddView(fab);
            #endregion

            #region activity_main
            drawer = new DrawerLayout(this);
            drawer.LayoutParameters = new DrawerLayout.LayoutParams(DrawerLayout.LayoutParams.MatchParent, DrawerLayout.LayoutParams.MatchParent);
            drawer.SetFitsSystemWindows(true);
            //tools:openDrawer="start"
            /*<include
    layout="@layout/app_bar_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />*/
            var navigationView = new NavigationView(this);
            navigationView.LayoutParameters = new NavigationView.LayoutParams(NavigationView.LayoutParams.WrapContent, NavigationView.LayoutParams.MatchParent);
            navigationView.SetForegroundGravity(GravityFlags.Start);
            navigationView.SetFitsSystemWindows(true);
            navigationView.AddHeaderView(nav_header_mainLayout); //app:headerLayout="@layout/nav_header_main" // (View)Resource.Layout.nav_header_main
            navigationView.InflateMenu(Resource.Menu.activity_main_drawer);//app:menu="@menu/activity_main_drawer"      

            drawer.AddView(navigationView);
            #endregion
            
            //this.SetContentView(mainLayout);//Resource.Layout.activity_main

            coordinatorLayout.AddView(content_mainLayout);
            drawer.AddView(coordinatorLayout);
            this.SetContentView(drawer);

            SetSupportActionBar(toolbar);//Resource.Id.toolbar
            fab.Click  = FabOnClick;//Resource.Id.fab

            toggle = new ActionBarDrawerToggle(this, drawer, toolbar, Resource.String.navigation_drawer_open, Resource.String.navigation_drawer_close);
            drawer.AddDrawerListener(toggle);//Resource.Id.drawer_layout
            toggle.SyncState();

            navigationView.SetNavigationItemSelectedListener((NavigationView.IOnNavigationItemSelectedListener)this);//Resource.Id.nav_view          
        }

        public override void OnBackPressed()
        {
            //DrawerLayout drawer = FindViewById<DrawerLayout>(Resource.Id.drawer_layout);
            if (drawer.IsDrawerOpen(GravityCompat.Start))
            {
                drawer.CloseDrawer(GravityCompat.Start);
            }
            else
            {
                base.OnBackPressed();
            }
        }

        public override bool OnCreateOptionsMenu(IMenu menu)
        {
            MenuInflater.Inflate(Resource.Menu.menu_main, menu);
            return true;
        }

        public override bool OnOptionsItemSelected(IMenuItem item)
        {
            int id = item.ItemId;
            if (id == Resource.Id.action_settings)
            {
                return true;
            }

            return base.OnOptionsItemSelected(item);
        }

        private void FabOnClick(object sender, EventArgs eventArgs)
        {
            View view = (View)sender;
            Snackbar.Make(view, "Replace with your own action", Snackbar.LengthLong)
                .SetAction("Action", (View.IOnClickListener)null).Show();
        }

        public bool OnNavigationItemSelected(IMenuItem item)
        {
            int id = item.ItemId;

            if (id == Resource.Id.nav_camera)
            {
                // Handle the camera action
            }
            else if (id == Resource.Id.nav_gallery)
            {

            }
            else if (id == Resource.Id.nav_slideshow)
            {

            }
            else if (id == Resource.Id.nav_manage)
            {

            }
            else if (id == Resource.Id.nav_share)
            {

            }
            else if (id == Resource.Id.nav_send)
            {

            }

            //DrawerLayout drawer = FindViewById<DrawerLayout>(Resource.Id.drawer_layout);
            drawer.CloseDrawer(GravityCompat.Start);
            return true;
        }

        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
        {
            Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}
  

Комментарии:

1. Почему вам нужно переделать xaml в код C #? Это увеличит сложность кода.

2. Для меня это пока невозможно, но я хочу попробовать

3. Я использовал вашу демонстрацию, когда я нажимаю кнопку hamburger, но navigationView не могу нажать вверх. Сравните с xml, я все еще не могу найти, где ошибка.