我有2个类,一个叫“ 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;

        }

    }


这是第二类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 !
            }
        }


因此,按原样调试此代码将返回“非静态字段,方法或属性需要对象引用”错误。

我正在将“ JS2CS”类称为用于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)的答案对我来说都很好。

提前致谢。

最佳答案

“非静态字段,方法或
  财产“


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

代替从Activity1参数化的JS2CS类构造函数创建Object或以静态方式访问View的方法来获取所有值:

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


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

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

10-08 12:09