簡體   English   中英

如何訪問片段類中MainActivity類的公共成員(變量或方法)

[英]how to access public Members(variable or method) of MainActivity class in fragment class

我有一個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。在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();

2 C#中的.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);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM