RunOnUiThread无法加载,需要对象引用(android)

本文关键字:对象引用 android 加载 RunOnUiThread | 更新日期: 2023-09-27 18:37:22

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

这是活动1的简短版本

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"类称为Web视图的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)的答案对我来说都很好。

提前谢谢。

RunOnUiThread无法加载,需要对象引用(android)

"非静态字段、方法或 物业"

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

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

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