RunOnUiThread 加载失败,需要对象引用 (android)

RunOnUiThread fails to load, An object reference is required (android)

我有 2 个 class,一个叫 "Activity1",第二个叫 "JS2CS"。在 JS2C 中,我正在尝试更新我在 Activity1 中声明的 android 小部件 (SwipeRefreshLayout),我需要该小部件是静态的(以防万一这很重要)。

这是 Activity1 的简短版本

public class Activity1 : Activity
    {
     public static SwipeRefreshLayout refresher;

     protected override void OnCreate (Bundle bundle)
        {
        base.OnCreate (bundle); 
        // Set our view from the "main" layout resource             
        SetContentView (Resource.Layout.Main);

        // The refresher - SwipeRefreshLayout
        refresher = FindViewById<SwipeRefreshLayout> (Resource.Id.refresher);
        refresher.SetColorScheme (Resource.Color.xam_dark_blue,
            Resource.Color.xam_purple,
            Resource.Color.xam_gray,
            Resource.Color.xam_green);
        refresher.Refresh += HandleRefresh;

        }

    }

这是第二个 class JS2CS

public class JS2CS : Java.Lang.Object, Java.Lang.IRunnable
        {
            Context context;

            public JS2CS (Context context)
            {
                this.context = context;
            }

            public void Run ()
            {
                Toast.MakeText (context, "true", ToastLength.Short).Show ();
                Activity1.RunOnUiThread (() => refresher.Enabled = false); // <-- error !               
            }
        }

因此调试此代码,因为它是 returns 一个 "An object reference is required for the nonstatic field, method, or property " 错误。

我将 "JS2CS" class 称为 Webview 的 java 库(它位于 Activity1 的 onCreate 中),以防万一:

        web_view = FindViewById<WebView> (Resource.Id.webview);
        web_view.SetWebViewClient (new webLinks ());
        web_view.Settings.JavaScriptEnabled = true;
        web_view.AddJavascriptInterface (new JS2CS (this), "JS2CS");

我正在使用 xamarin (c#),但两种语言(c# 和 java)的答案对我来说都很好。

提前致谢。

"An object reference is required for the nonstatic field, method, or property "

因为这里 Activity1.RunOnUiThread 您试图在不使用实例的情况下从 Activity 访问 non-static 方法 RunOnUiThread

不是从 Activity1 参数化 JS2CS class 构造函数以静态方式创建对象或访问视图以获取所有值:

Activity activity;
SwipeRefreshLayout refresher
public JS2CS (Context context,Activity activity,
                                      SwipeRefreshLayout refresher)
   {
     this.context = context;
     this.activity=activity;
     this.refresher=refresher;
   }

现在调用 RunOnUiThread 为:

activity.RunOnUiThread (() => refresher.Enabled = false);

并在 activity 中将 JS2CS 对象传递给 AddJavascriptInterface 方法,如下所示:

web_view.AddJavascriptInterface (new JS2CS (this,this,refresher),"JS2CS");