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

时间:2015-01-14 06:11:54

标签: java c# android xamarin

我有两个类叫做“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)的答案都很好。

提前致谢。

1 个答案:

答案 0 :(得分:2)

  

“非静态字段,方法或者需要对象引用   财产“

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

而不是从JS2CS参数化Activity activity; SwipeRefreshLayout refresher public JS2CS (Context context,Activity activity, SwipeRefreshLayout refresher) { this.context = context; this.activity=activity; this.refresher=refresher; } 类构造函数以静态方式创建Object或访问View以获取所有值:

RunOnUiThread

现在将activity.RunOnUiThread (() => refresher.Enabled = false); 称为:

JS2CS

在活动中将AddJavascriptInterface对象传递给web_view.AddJavascriptInterface (new JS2CS (this,this,refresher),"JS2CS"); 方法为:

{{1}}