2015-01-03 30 views
3

这听起来可能是一个愚蠢的问题,但由于我对Xamarin相当陌生,因此我会为此付出代价。如何从Xamarin.Forms中的可移植类库项目调用位于Android项目中的方法?

所以我有一个Xamarin.Forms解决方案,还有一个Android项目加上一个可移植类库。我从Android项目中的MainActivity.cs调用起始页面,该页面本身从可移植类库项目中定义的表单(通过调用App.GetMainPage())调用第一页。现在,我想在我的一个表单上添加点击事件来获取设备的当前位置。显然,为了获得我必须在Android项目中实现的位置。那么,如何从可移植类库项目中的Click事件调用GetLocation方法?任何帮助,将不胜感激。对不起,可能有重复。

+0

对不起,它是重复的! http://stackoverflow.com/questions/25588557/xamarin-forms-get-data-from-device-specific-code-back-to-the-forms?rq=1 http://developer.xamarin.com /导游/跨平台/ xamarin表单/依存服务/ – Moji

回答

9

如果您使用Xamarin.Forms.Labs,解决方案确实在提供的链接中。如果你只使用Xamarin.Forms,它几乎是你必须通过使用DependencyService来做同样的事情。这比看起来更容易。 http://developer.xamarin.com/guides/cross-platform/xamarin-forms/dependency-service/

我建议读这篇文章,我几乎打破了我的大脑试图理解。 http://forums.xamarin.com/discussion/comment/95717

为了方便起见,这里的工作的例子,如果你尚未完成你的工作,你可以适应:

创建您的Xamarin.Forms项目的接口。

using Klaim.Interfaces; 
using Xamarin.Forms; 

namespace Klaim.Interfaces 
{ 
    public interface IImageResizer 
    { 
     byte[] ResizeImage (byte[] imageData, float width, float height); 
    } 
} 

在Android项目中创建服务/自定义渲染器。

using Android.App; 
using Android.Graphics; 
using Klaim.Interfaces; 
using Klaim.Droid.Renderers; 
using System; 
using System.IO; 
using Xamarin.Forms; 
using Xamarin.Forms.Platform.Android; 

[assembly: Xamarin.Forms.Dependency (typeof (ImageResizer_Android))] 
namespace Klaim.Droid.Renderers 
{ 
    public class ImageResizer_Android : IImageResizer 
    { 
     public ImageResizer_Android() {} 
     public byte[] ResizeImage (byte[] imageData, float width, float height) 
     { 

      // Load the bitmap 
      Bitmap originalImage = BitmapFactory.DecodeByteArray (imageData, 0, imageData.Length); 
      Bitmap resizedImage = Bitmap.CreateScaledBitmap(originalImage, (int)width, (int)height, false); 

      using (MemoryStream ms = new MemoryStream()) 
      { 
       resizedImage.Compress (Bitmap.CompressFormat.Jpeg, 100, ms); 
       return ms.ToArray(); 
      } 
     } 
    } 
} 

所以,当你调用这个:

byte[] test = DependencyService.Get<IImageResizer>().ResizeImage(AByteArrayHereCauseFun, 400, 400); 

它执行的Android代码,并返回值到您的表单项目。

相关问题