当前位置: 代码迷 >> 综合 >> xamarin.forms跳转android native并传参
  详细解决方案

xamarin.forms跳转android native并传参

热度:47   发布时间:2023-12-22 06:42:42.0

xamarin开发过程中,能写在pcl的尽量写在pcl,提高复用率,但有时候因为一些已知的原因,不得不去使用native,xamarin官方github上有提供这部分源码Forms2Native供参考,这里以实际开发过程中实现xamarin android截图控件为例。

一、pcl中:SourcePage为调用方,CropPage.cs为目标页;

public SourcePage()
{InitializeComponent();var command = new Command(async () =>{//获取gallery中照片var mediaPicker = DependencyService.Get<IMediaPicker>();var result = await mediaPicker.SelectPhotoAsync(new CameraMediaStorageOptions { DefaultCamera = CameraDevice.Front, MaxPixelDimension = 400 });//创建CropPage并传入照片路径var desPage = new CropPage(result.Path);//跳转App.Current.MainPage = desPage;//跳转后会出现两个页面,实际上CropPage还是生成了,在点击左下方的返回按钮时回到的是CropPage而不是SourcePagae,//我这里是将原调用页重新指定回去,不知道其他人是怎么处理的,欢迎告知。App.Current.MainPage = new SourcePage();}); btnSelectPhoto.Command = command; 
}

 
  
 

 
  
 

二、CropPage.cs

public class CropPage : ContentPage
{//欲传往native的参数,写成公共属性供native中Renderers的OnCreate方法调用,这里为图片路径public string FilePath { get; set; }public CropPage(){}public CropPage(string filePath):this(){FilePath = filePath;}
}

三、xamarin android中,特定Renderer绑定CropPage和Renderer本身,这里为CropPageRenderer

//该特性实现CropPage和CropPageRenderer的绑定
[assembly:ExportRenderer(typeof(AppPortable.CropPage), typeof(App.Droid.Renderers.CropPageRenderer))]namespace App.Droid.Renderers
{public class CropPageRenderer : PageRenderer{protected override void OnElementChanged(ElementChangedEventArgs<Page> e){base.OnElementChanged(e);var filePath = "";if (e.NewElement != null){//这边获取CropPage所传递的参数filePath = (e.NewElement as CropPage).FilePath;}//开始运行指定的Activity,这里是CropActivityvar activity = this.Context as Activity;var cropActivity = new Intent(activity, typeof(CropActivity));activity.StartActivity(cropActivity);}}
}

四、xamarin android中的CropActivity.cs

namespace App.Droid
{[Activity(Label = "CropActivity")]public class CropActivity : Activity{protected override void OnCreate(Bundle savedInstanceState){base.OnCreate(savedInstanceState);//这边就完成了,至于layout目录下的axml目标axmlSetContentView(Resource.Layout.CropImage);}}
}

 
 




  相关解决方案