如何访问片段类中MainActivity类的公共成员(变量或方法)

时间:2019-07-12 10:46:49

标签: c# xamarin.android fragment

我有一个Xamarin-Android应用程序,其中使用了片段。我想在片段类中访问MainActivity的公共方法。

webview_download+=mWebViewDownload

但是此方法mWebViewDownload在MainActivity中定义。我无法从片段访问此方法。

我试图使此方法静态化,但是此方法使用的服务必须在没有实例的情况下才能访问。    我试图通过this.mWebViewDownload访问,但错误是未在该范围内定义mWebViewDownload。  我为它搜索stackoverflow,大多数问题建议getActivity()但这是与Java相关的解决方案,但我需要与C#相关的解决方案。   我试图通过MainActivity.mWebViewDownload访问它,但是它也给出了这样的错误:没有像这样的对象引用就无法访问非静态对象。请help.fragment类如下:

        internal class WebviewFragment : Fragment
        {
            public const string ARG_NUMBER = "number";

            public WebviewFragment()
            {
                // Empty constructor required for fragment subclasses
            }

            public static Fragment NewInstance(int position)
            {

                Fragment fragment = new WebviewFragment();
                Bundle args = new Bundle();
                args.PutInt(WebviewFragment.ARG_NUMBER, position);
                fragment.Arguments = args;
                return fragment;
            }

            public override View OnCreateView(LayoutInflater inflater, ViewGroup container,
                                               Bundle savedInstanceState)
            {
                View rootView = inflater.Inflate(Resource.Layout.fragment_content2, container, false);
                var i = this.Arguments.GetInt(ARG_NUMBER);
                var url = this.Resources.GetStringArray(Resource.Array.weburls_array)[i];

                var title = this.Resources.GetStringArray(Resource.Array.contents_array)[i];
                // show progress bar

                progressBar = (ProgressBar)rootView.FindViewById<ProgressBar>(Resource.Id.progressBar1);
                var web_view = rootView.FindViewById<WebView>(Resource.Id.webview);

                web_view.SetWebViewClient(new HelloWebViewClient());

                web_view.Settings.JavaScriptCanOpenWindowsAutomatically = true;
                web_view.Settings.JavaScriptEnabled = true;
                web_view.Download += Mwebview_Download;// here is error
                //set the custom web client
                web_view.SetWebViewClient(new JavaScriptWebViewClient());

                web_view.LoadUrl(url);


                this.Activity.Title = title;
                return rootView;
            }
        }

这是MainActivity类中的mWebView_Download方法

 // Download
        public void Mwebview_Download(object sender, DownloadEventArgs e)
        {
            var listPermissions = new System.Collections.Generic.List<string>();

            if (CheckSelfPermission(Android.Manifest.Permission.WriteExternalStorage) != Permission.Granted)
            {
                Log.Warn(LOG_TAG, "CheckSelfPermission(WriteExternalStorage) not yet granted - will prompt user for permission");
                listPermissions.Add(Android.Manifest.Permission.WriteExternalStorage);


                // Make the request with the permissions needed...and then check OnRequestPermissionsResult() for the results
                RequestPermissions(listPermissions.ToArray(), PERMISSION_Write_External_Storage);
            }
            else
            {

                var url = e.Url;

                DownloadManager.Request request = new DownloadManager.Request(Android.Net.Uri.Parse(url));

                request.AllowScanningByMediaScanner();
                string filename = System.IO.Path.GetFileName(url);


                request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);
                //  request.SetNotificationVisibility(DownloadManager.Request.VisibilityVisibleNotifyCompleted); //Notify client once download is completed!

                request.SetDestinationInExternalPublicDir(Android.OS.Environment.DirectoryDownloads, filename);
                DownloadManager dm = (DownloadManager)GetSystemService("download");
                dm.Enqueue(request);
                Toast.MakeText(ApplicationContext, "Downloading File", ToastLength.Long//To notify the Client that the file is being downloaded
                            ).Show();
            }
        }
       ```

1 个答案:

答案 0 :(得分:1)

解决方案:

1 。在MainActivity中定义静态属性,然后在Fragment中使用它,例如:

public class MainActivity : AppCompatActivity
{
    public static MainActivity Instance;
    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        SetContentView(Resource.Layout.activity_main);

        Instance = this;
    }   
    public void test()
    {

    }
}

然后在您的片段中,可以通过以下方式访问该方法:

MainActivity.Instance.test();
C#中的

2 .getActivity()方法为((ActivityType)Activity).yourPublicMethod(); :

 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);

        ((MainActivity)Activity).test();

        return base.OnCreateView(inflater, container, savedInstanceState);
    }