简体   繁体   中英

Xamarin how to open xamarin forms page from android project?

I want to open Xamarin forms page from Xamarin Android project. On android project I created toolabar item image, where I am calling event to open page from Xamarin forms project.

Here is my MainActivity.cs toolabar image item implementation:

    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
    {
      private IMenu CurrentMenu { get; set; }
      private ImageView imgSmallC { get; set; }

      public override bool OnCreateOptionsMenu(IMenu menu)
            {
               ActionBar.DisplayOptions = ActionBarDisplayOptions.HomeAsUp | ActionBarDisplayOptions.ShowCustom | ActionBarDisplayOptions.ShowTitle | ActionBarDisplayOptions.ShowHome;  
                LayoutInflater inflater = (LayoutInflater)ActionBar.ThemedContext.GetSystemService(LayoutInflaterService);
                View customActionBarView = inflater.Inflate(Resource.Layout.actionbar_custom_view_done, null);  

                imgSmallC = (ImageView)customActionBarView.FindViewById<ImageView>(Resource.Id.ImgSmallC);

                imgSmallC.Click += (object sender, EventArgs args) =>
                {
                    StartActivity(typeof(MyPopupPage));
                };
                return base.OnCreateOptionsMenu(menu);
            }
}

In StartActivity I am calling MyPopupPage.xaml page from Xamarin forms project, but unfortunately when I am debugging project and I click on toolbar image I get such a error:

System.ArgumentException: type Parameter name: Type is not derived from a java type.

You can not use a Xamarin.Form based Page as an Android Activity , they are two completely different things .

You can access the Xamarin.Forms Application singleton from the Xamarin.Android project and use that to PushModelAsync or PushAsync

Example (using full Namespace):

    await Xamarin.Forms.Application.Current.MainPage.Navigation.PushModalAsync(new PushPageFromNative.MyPage());

A Dependency Service -based Example:

Interface:

using System;
namespace PushPageFromNative
{
    public interface IShowForm
    {
        void PushPage();
    }
}

Xamarin.Form -based code:

var pushFormBtn = new Button
{
    Text = "Push Form",
    VerticalOptions = LayoutOptions.CenterAndExpand,
    HorizontalOptions = LayoutOptions.CenterAndExpand,
};
pushFormBtn.Clicked += (sender, e) =>
{
        DependencyService.Get<IShowForm>().PushPage();
};

Xamarin.Android Dependancy Implementation:

async public void PushPage()
{
    // Do some Android specific things... and then push a new Forms' Page
    await Xamarin.Forms.Application.Current.MainPage.Navigation.PushModalAsync(new PushPageFromNative.MyPage());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM