片段导航使用地图Xamarin Android

时间:2018-03-07 19:00:20

标签: xamarin.android

我遇到的问题是,当我浏览应用程序时,当我第一次初始化包含地图的片段时,它会很好地初始化,但是当我导航到不同的片段并再次回到包含地图的片段时,它会给出初始化'查看对象' 时出错,错误截图附于下方。请帮帮我。

主要活动代码

    DrawerLayout drawerLayout;
    NavigationView navigationView;
    IMenuItem previousItem;
    TextView UserNameTxt;
    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.main);
        var toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
        if (toolbar != null)
        {
            SetSupportActionBar(toolbar);
            SupportActionBar.SetDisplayHomeAsUpEnabled(true);
            SupportActionBar.SetHomeButtonEnabled(true);
        }

        drawerLayout = FindViewById<DrawerLayout>(Resource.Id.drawer_layout);

        //Set hamburger items menu
        SupportActionBar.SetHomeAsUpIndicator(Resource.Drawable.ic_menu);

        //setup navigation view
        navigationView = FindViewById<NavigationView>(Resource.Id.nav_view);
        var headerview = navigationView.GetHeaderView(0);
        UserNameTxt = headerview.FindViewById<TextView>(Resource.Id.UserNameTxt);
        UserNameTxt.Text = "Yousuf";
        //handle navigation
        navigationView.NavigationItemSelected += (sender, e) =>
        {
            if (previousItem != null)
                previousItem.SetChecked(false);

            navigationView.SetCheckedItem(e.MenuItem.ItemId);

            previousItem = e.MenuItem;

            switch (e.MenuItem.ItemId)
            {
                case Resource.Id.menuTracking:
                    ListItemClicked(2);
                    break;
                case Resource.Id.menuHoldingRoutine:
                    ListItemClicked(0);
                    break;
                case Resource.Id.menuCalendarEvent:
                    ListItemClicked(1);
                    break;
                case Resource.Id.menuSettings:
                    StartActivity(typeof(SettingActivity));
                    break;
            }


            drawerLayout.CloseDrawers();
        };


        //if first time you will want to go ahead and click first item.
        if (savedInstanceState == null)
        {
            navigationView.SetCheckedItem(Resource.Id.menuHoldingRoutine);
            ListItemClicked(0);
        }
    }


    int oldPosition = -1;
    private void ListItemClicked(int position)
    {
        //this way we don't load twice, but you might want to modify this a bit.
        if (position == oldPosition)
            return;

        oldPosition = position;

        Fragment fragment = null;
        switch (position)
        {
            case 0:
                fragment = HoldingRoutineFragment.NewInstance();
                //fragment = Fragment1.NewInstance();
                break;
            case 1:
                fragment = CalendarEventFragment.NewInstance();
                //fragment = Fragment2.NewInstance();
                break;
            case 2:
                fragment = TrackingFragment.NewInstance();
                break;
        }
        FragmentTransaction fragmentTx = this.FragmentManager.BeginTransaction();
        fragmentTx.Replace(Resource.Id.content_frame, fragment);
        fragmentTx.AddToBackStack(null);
        fragmentTx.Commit();
        //SupportFragmentManager.BeginTransaction()
        //    .Replace(Resource.Id.content_frame, fragment)
        //    .Commit();
    }

    public override bool OnOptionsItemSelected(IMenuItem item)
    {
        switch (item.ItemId)
        {
            case Android.Resource.Id.Home:
                drawerLayout.OpenDrawer(GravityCompat.Start);
                return true;
        }
        return base.OnOptionsItemSelected(item);
    }
}

MainActivity的Xml代码

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">
<!-- The main content view -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <android.support.design.widget.AppBarLayout
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:id="@+id/toolbar_layout">
            <include
                android:id="@+id/toolbar"
                layout="@layout/toolbar"
                app:layout_scrollFlags="scroll|enterAlways" />
        </android.support.design.widget.AppBarLayout>
        <FrameLayout
            android:id="@+id/content_frame"
            android:layout_below="@id/toolbar_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </RelativeLayout>
    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:headerLayout="@layout/nav_header"
        app:menu="@menu/nav_menu"
        android:fitsSystemWindows="true" />
</android.support.v4.widget.DrawerLayout>

跟踪片段代码

using Android.OS;
using Android.Views;
using System;
using System.Collections.Generic;
using Android.Widget;
using Android.App;
using Android.Gms.Maps;
using Android.Gms.Maps.Model;
using System.Timers;
using Android.Graphics;
using Android.Content;

namespace RoutineApp.Fragments
{
    public class TrackingFragment : Fragment, IOnMapReadyCallback
    {
        private GoogleMap gMap;
        private MapFragment mapFragment;
        private LatLng oldposition;
        private MarkerOptions markerOptions;
        private Marker marker;
        private Timer timer;
        private int timercount = 0;
        private Button BtnUp, BtnDown, BtnRight, BtnLeft, BtnDirection;
        public override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Create your fragment here
        }
        public static TrackingFragment NewInstance()
        {
            var frag1 = new TrackingFragment { Arguments = new Bundle() };
            return frag1;
        }
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            // Use this to return your custom view for this Fragment
            // return inflater.Inflate(Resource.Layout.YourFragment, container, false);

            var ignore = base.OnCreateView(inflater, container, savedInstanceState);
            var view = inflater.Inflate(Resource.Layout.tracking, container, false);
            mapFragment = FragmentManager.FindFragmentById<MapFragment>(Resource.Id.TrackingMap);
            mapFragment.GetMapAsync(this);
            BtnUp = view.FindViewById<Button>(Resource.Id.Up_btn);
            BtnDown = view.FindViewById<Button>(Resource.Id.Down_btn);
            BtnLeft = view.FindViewById<Button>(Resource.Id.Left_btn);
            BtnRight = view.FindViewById<Button>(Resource.Id.Right_btn);
            BtnDirection = view.FindViewById<Button>(Resource.Id.Direction_btn);
            return view; 
        }

        public void OnMapReady(GoogleMap googleMap)
        {
            gMap = googleMap;
            gMap.UiSettings.SetAllGesturesEnabled(true);
            gMap.UiSettings.ZoomControlsEnabled = true;
            gMap.UiSettings.CompassEnabled = true;
            gMap.UiSettings.MyLocationButtonEnabled = true;

            LatLng latLng = new LatLng(24.9288, 67.0402);
            oldposition = latLng;

            CameraUpdate camera = CameraUpdateFactory.NewLatLngZoom(latLng, 19);
            gMap.MoveCamera(camera);

            markerOptions = new MarkerOptions()
                .SetPosition(latLng)
                .SetTitle("Current Position")
                .Draggable(true);
            marker = gMap.AddMarker(markerOptions);

            BtnUp.Click += BtnUp_Click;
            BtnDown.Click += BtnDown_Click;
            BtnLeft.Click += BtnLeft_Click;
            BtnRight.Click += BtnRight_Click;
            BtnDirection.Click += BtnDirection_Click;
            //gmaps.MarkerClick += Gmaps_MarkerClick;
            gMap.MarkerDragEnd += GMap_MarkerDragEnd;
        }
        private void BtnDirection_Click(object sender, EventArgs e)
        {
            var intent = new Intent(this.Activity, typeof(GoogleMapDirectionsActivity));
            StartActivity(intent);
        }

        private void MarkerSetting(LatLng newlatlng, LatLng oldlatlng)
        {
            markerOptions = new MarkerOptions()
                .SetPosition(newlatlng)
                .SetTitle("Current Position")
                .Draggable(true);
            marker = gMap.AddMarker(markerOptions);
            PolylineOptions line = new PolylineOptions().Add(newlatlng).Add(oldlatlng).InvokeColor(Color.Red);
            Polyline polyline = gMap.AddPolyline(line);
            oldposition = newlatlng;
        }
        private void BtnRight_Click(object sender, EventArgs e)
        {
            if (marker != null)
            {
                marker.Remove();
            }
            timercount = 0;
            LatLng newposition = new LatLng(oldposition.Latitude, oldposition.Longitude);
            newposition.Longitude = newposition.Longitude + 0.00001;
            MarkerSetting(newposition, oldposition);
        }

        private void BtnLeft_Click(object sender, EventArgs e)
        {
            if (marker != null)
            {
                marker.Remove();
            }
            timercount = 0;
            LatLng newposition = new LatLng(oldposition.Latitude, oldposition.Longitude);
            newposition.Longitude = newposition.Longitude - 0.00001;
            MarkerSetting(newposition, oldposition);
        }

        private void BtnDown_Click(object sender, EventArgs e)
        {
            if (marker != null)
            {
                marker.Remove();
            }
            timercount = 0;
            LatLng newposition = new LatLng(oldposition.Latitude, oldposition.Longitude);
            newposition.Latitude = newposition.Latitude - 0.00001;
            MarkerSetting(newposition, oldposition);
        }

        private void BtnUp_Click(object sender, EventArgs e)
        {
            if (marker != null)
            {
                marker.Remove();
            }
            timercount = 0;
            LatLng newposition = new LatLng(oldposition.Latitude, oldposition.Longitude);
            newposition.Latitude = newposition.Latitude + 0.00001;
            MarkerSetting(newposition, oldposition);
        }
        private void GMap_MarkerDragEnd(object sender, GoogleMap.MarkerDragEndEventArgs e)
        {
            timercount = 0;
            LatLng newpositon = e.Marker.Position;
            PolylineOptions line = new PolylineOptions().Add(newpositon).Add(oldposition).InvokeColor(Color.Red);
            Polyline polyline = gMap.AddPolyline(line);
            oldposition = newpositon;
        }
        public override void OnResume()
        {
            base.OnResume();
            timer = new Timer();
            timer.Interval = 1000;
            timer.Elapsed += Timer_Elapsed;
            timer.Start();
        }

        private void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (timercount < 10)
            {
                timercount++;
            }
            else
            {
                Activity.RunOnUiThread(() =>
                {
                    CreateCircle();
                });
            }
        }

        private void CreateCircle()
        {
            CircleOptions circle = new CircleOptions();
            circle.InvokeCenter(oldposition);
            circle.InvokeRadius(1);
            circle.InvokeStrokeColor(Color.Blue);
            circle.InvokeFillColor(Color.LightSkyBlue);
            gMap.AddCircle(circle);
            timercount = 0;
        }
    }
}

跟踪片段的Xml代码

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/super_map_container">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/map_container"
        android:weightSum="100">
        <fragment
            android:id="@+id/TrackingMap"
            android:layout_height="0dp"
            android:layout_width="match_parent"
            android:name="com.google.android.gms.maps.MapFragment"
            android:layout_weight="90" />
        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="10"
            android:weightSum="10">
            <Button
                android:id="@+id/Up_btn"
                android:layout_height="match_parent"
                android:layout_width="20dp"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:background="#A11"
                android:layout_weight="2" />
            <Button
                android:id="@+id/Down_btn"
                android:layout_height="match_parent"
                android:layout_width="20dp"
                android:layout_marginRight="10dp"
                android:background="#B22"
                android:layout_weight="2" />
            <Button
                android:id="@+id/Left_btn"
                android:layout_height="match_parent"
                android:layout_width="20dp"
                android:layout_marginRight="10dp"
                android:background="#C33"
                android:layout_weight="2" />
            <Button
                android:id="@+id/Right_btn"
                android:layout_height="match_parent"
                android:layout_width="20dp"
                android:layout_marginRight="10dp"
                android:background="#D44"
                android:layout_weight="2" />
            <Button
                android:id="@+id/Direction_btn"
                android:layout_height="match_parent"
                android:layout_width="20dp"
                android:layout_marginRight="10dp"
                android:background="#E55"
                android:layout_weight="2" />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

Error Screen Shot

1 个答案:

答案 0 :(得分:0)

在跟踪片段中将您的片段代码更改为此代码,然后重试:

    <fragment
     android:id="@+id/map"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:layout_weight="90"
     class="com.google.android.gms.maps.MapFragment" />

如果它没有工作,请退回