【问题标题】:Is there a way to pass list from android project to MainPage in xamarin.forms project有没有办法将列表从 android 项目传递到 xamarin.forms 项目中的 MainPage
【发布时间】:2021-06-08 06:43:48
【问题描述】:

我的 android 项目中有 CustomMapRenderer 类,当您在地图上按下标记时,列表将使用以下代码从数据库中填充:

    using System;
using System.Collections.Generic;
using System.Linq;
using Android.Content;
using Android.Gms.Maps;
using Android.Gms.Maps.Model;
using Android.Widget;
using MaritsaTundzhaForecast;
using MaritsaTundzhaForecast.Models;
using MaritsaTundzhaForecast.Droid;
using MySqlConnector;
using Xamarin.Forms;
using Xamarin.Forms.Maps;
using Xamarin.Forms.Maps.Android;

[assembly: ExportRenderer(typeof(CustomMap), typeof(CustomMapRenderer))]
namespace MaritsaTundzhaForecast.Droid
{
    public class CustomMapRenderer : MapRenderer, GoogleMap.IInfoWindowAdapter
    {
        List<CustomPin> customPins;

        public CustomMapRenderer(Context context) : base(context)
        {
        }

        protected override void OnElementChanged(Xamarin.Forms.Platform.Android.ElementChangedEventArgs<Map> e)
        {
            base.OnElementChanged(e);

            if (e.OldElement != null)
            {
                NativeMap.InfoWindowClick -= OnInfoWindowClick;
            }

            if (e.NewElement != null)
            {
                var formsMap = (CustomMap)e.NewElement;
                customPins = formsMap.CustomPins;
            }
        }

        protected override void OnMapReady(GoogleMap map)
        {
            base.OnMapReady(map);

            NativeMap.InfoWindowClick += OnInfoWindowClick;
            NativeMap.SetInfoWindowAdapter(this);
        }

        protected override MarkerOptions CreateMarker(Pin pin)
        {
            var marker = new MarkerOptions();
            marker.SetPosition(new LatLng(pin.Position.Latitude, pin.Position.Longitude));
            marker.SetTitle(pin.Label);
            marker.SetSnippet(pin.Address);
            //marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.green));

            var custom = customPins.Where(x => x.Label == pin.Label && x.Address == pin.Address).FirstOrDefault();

            if (custom != null)
            {
                if (custom.AlertLevel == 1)
                {
                    marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.green));
                }
                if (custom.AlertLevel == 2)
                {
                    marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.yellow));
                }
                if (custom.AlertLevel == 3)
                {
                    marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.orange));
                }
                if (custom.AlertLevel == 4)
                {
                    marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.red));
                }
            }
            return marker;
        }

        void OnInfoWindowClick(object sender, GoogleMap.InfoWindowClickEventArgs e)
        {
            var customPin = GetCustomPin(e.Marker);
            if (customPin == null)
            {
                throw new Exception("Custom pin not found");
            }

            if (!string.IsNullOrWhiteSpace(customPin.Url))
            {
                var url = Android.Net.Uri.Parse(customPin.Url);
                var intent = new Intent(Intent.ActionView, url);
                intent.AddFlags(ActivityFlags.NewTask);
                Android.App.Application.Context.StartActivity(intent);
            }
        }

        public Android.Views.View GetInfoContents(Marker marker)
        {
            var inflater = Android.App.Application.Context.GetSystemService(Context.LayoutInflaterService) as Android.Views.LayoutInflater;
            if (inflater != null)
            {
                Android.Views.View view;

                var customPin = GetCustomPin(marker);
                if (customPin == null)
                {
                    throw new Exception("Custom pin not found");
                }

                if (customPin.Name.Equals("Xamarin"))
                {
                    view = inflater.Inflate(Resource.Layout.XamarinMapInfoWindow, null);
                }
                else
                {
                    view = inflater.Inflate(Resource.Layout.MapInfoWindow, null);
                }

                CustomPin pin = GetCustomPin(marker);

                int CodeNum = pin.CodeNum;
                int AlertLevel = pin.AlertLevel;

                var infoTitle = view.FindViewById<TextView>(Resource.Id.InfoWindowTitle);
                var infoSubtitle = view.FindViewById<TextView>(Resource.Id.InfoWindowSubtitle);
                var infoSubtitle2 = view.FindViewById<TextView>(Resource.Id.InfoWindowSubtitle2);
                var infoSubtitle3 = view.FindViewById<TextView>(Resource.Id.InfoWindowSubtitle3);

                if (infoTitle != null)
                {
                    infoTitle.Text = marker.Title;
                }
                if (infoSubtitle != null)
                {
                    infoSubtitle.Text = marker.Snippet;
                }
                if (infoSubtitle2 != null)
                {
                    infoSubtitle2.Text = "Тревога: (1-4): " + AlertLevel;
                }
                if (infoSubtitle3 != null)
                {
                    infoSubtitle3.Text = "Код на станция: " + CodeNum;
                }

                return view;
            }
            return null;
        }

        public Android.Views.View GetInfoWindow(Marker marker)
        {
            return null;
        }

        public IEnumerable<AlertLevel> DataBaseConnection(int mapCode)
        {
            string ConnectionString = "server=192.168.0.1;uid=username;port=3389;pwd=password;database=dbName;";
            MySqlConnection Conn = new MySqlConnection(ConnectionString);
            var listAlert = new List<AlertLevel>();

            try
            {
                Conn.Open();

                //replace(2) with mapCode
                string query = "CALL Get_Alert_levels_Station(" + mapCode + ");";
                MySqlCommand myCommand = new MySqlCommand(query, Conn);
                MySqlDataReader myReader;

                myReader = myCommand.ExecuteReader();

                try
                {
                    while (myReader.Read())
                    {
                        var currentData = new AlertLevel()
                        {
                            dateForecast = myReader.GetDateTime(0),
                            levelForecast = myReader.GetInt32(1)
                        };

                        listAlert.Add(currentData);
                    } 
                }
                finally
                {
                    myReader.Close();
                    Conn.Close();
                }
            }

            catch (Exception ex)
            {
                Console.WriteLine("Database Connection", "Not Connected ..." + ex.ToString(), "OK");
            }

            return listAlert;
        }

        CustomPin GetCustomPin(Marker annotation)
        {
            string id = annotation.Id.Substring(1);

            int mapCode = int.Parse(id);

            var result = DataBaseConnection(mapCode);

            MessagingCenter.Send(this, "PinSelected", result);

            var position = new Position(annotation.Position.Latitude, annotation.Position.Longitude);

            foreach (var pin in customPins)
            {
                if (pin.Position == position)
                {
                    return pin;
                }
            }
            return null;
        }
    }
}

GetCustomPin方法中我要传递给MainPage.cs这行代码:

var result = DataBaseConnection(mapCode);

以同样的方法,我尝试通过这行代码:

MessagingCenter.Send(this, "PinSelected", result);

所以我删除了android项目中的AlertLevel.cs对象,并在xamarin.forms项目中创建了一个新对象AlertLevel.cs。在MainPage.cs 中,我将using MaritsaTundzhaForecast.Models; 设置为使用AlertLevel.cs,并使用此代码尝试从android 项目接收方法:

MessagingCenter.Subscribe<CustomMapRenderer, IEnumerable<AlertLevel>>(this, "PinSelected", async (sender, arg) =>
        {
            // do something here with arg, which is IEnumerable<AlertLevel>
        });

但我收到错误:

The type or namespace name 'CustomMapRenderer' could not be found (are you missing a using directive or an assembly reference?)

有没有办法解决这个问题,我如何用来自CustomMapRendererresult 填充来自MainPageListView

【问题讨论】:

标签: c# android xamarin


【解决方案1】:

MainPage 中使用MessagingCenter 来监听来自地图控件的消息

MessagingCenter.Subscribe<object, IEnumerable<AlertLevel>>(this, "PinSelected", async (sender, arg) =>
{
    // do something here with arg, which is IEnumerable<AlertLevel>
});

在您的地图渲染器中,以result 作为参数发送消息

MessagingCenter.Send<object, IEnumerable<AlertLevel>>(this, "PinSelected", result);

【讨论】:

  • 有没有办法修复 CustomMapRenderer 错误:在 MainPage 中找不到类型或命名空间名称“CustomMapRenderer”(您是否缺少 using 指令或程序集引用?)?
  • BOTH MessagingCenter 调用中将 CustomMapRenderer 替换为 object
  • 如何在 MainPage 中调用 result 以及在 MainPage 中的哪个方法中我必须在按下标记时放置此代码? OnAppearing ?
  • // do something here --> 这是您在收到消息时放置要调用的代码的位置。通常你会在页面构造函数中添加Subscribe
  • 然后将 arg 分配给您的 ListView 的 ItemsSource
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-15
  • 2017-06-23
  • 2021-07-09
  • 2018-08-18
  • 2022-06-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多