非静态字段,方法或属性

时间:2018-03-23 13:04:24

标签: c# android xamarin

查看此How to show loading image or progress bar on WebView,它清楚地表明以下方法应该有效但我遇到了问题,因为我无法访问ProgressBar中的public override void OnPageFinished(WebView view, string url)

我的代码如下

webView.Settings.JavaScriptEnabled = true;
webView.Settings.LoadWithOverviewMode = true;
webView.Settings.UseWideViewPort = true;
webView.SetWebViewClient(new WebViewClientClass());                    
webView.LoadDataWithBaseURL("file:///android_asset/", HTML_DATA, "text/html", "UTF-8", null);

我的WebViewClientClass是以下

#region Webview URL handler
internal class WebViewClientClass : WebViewClient
{    
    public override bool ShouldOverrideUrlLoading(WebView view, IWebResourceRequest request)
    {
        Android.Net.Uri url = request.Url;
        view.LoadUrl(url.ToString());
        return true;
    }

    public override void OnPageStarted(WebView view, string url, Bitmap favicon)
    {
         base.OnPageStarted(view, url, favicon);
         Log.Info("101028", "loading started");
    }

    public override void OnPageFinished(WebView view, string url)
    {
        base.OnPageFinished(view, url);
        Log.Info("101028", "loading finised");
        PB.Visibility = ViewState.Gone; ***<<<<<<<------ ERROR HERE***
    }
}
#endregion

我可以在logcat中看到结果但是当我尝试在ProgressBar方法中访问PB.Visibility = ViewState.Gone OnPageFinished时 - 我收到以下错误

  

ERROR

非静态字段,方法或属性需要对象引用

PogressBar代码

private ProgressBar PB;

protected override async void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState); 
    SetContentView(Resource.Layout.Read);
    PB = FindViewById<ProgressBar>(Resource.Id.MyProgressBar);
}

任何人都知道什么是正确的方法?我如何做这项工作

干杯

1 个答案:

答案 0 :(得分:1)

在您的代码中,您的ProgressBar似乎属于您的Activity,并且您正试图在WebViewClientClass中访问它,这就是您丢失对象引用的原因。

所以你应该在你的活动类中有一个隐藏/显示ProgressBar的方法,并且必须有某种回调机制来调用这个方法

定义如下界面

interface ProgressBarHandler{
    public void hideProgress();
} 

在您的活动类中实现此接口

class MyActivity extends Activity implements ProgressBarHandler{
    //other usual things in your activity

    protected override async void OnCreate(Bundle savedInstanceState){
        //here pass the activity instance to WebViewClientClass
        webView.SetWebViewClient(new WebViewClientClass(this)); 
    }

    public void hideProgress(){
        PB.Visibility = ViewState.Gone;
    }
}

最后在你的WebViewClientClass

class WebViewClientClass : WebViewClient
{    
    private ProgressBarHandler handler;
    public WebViewClientClass(ProgressBarHandler handler){
        this.handler = handler;
    }

    public override void OnPageFinished(WebView view, string url)
    {
        base.OnPageFinished(view, url);
        Log.Info("101028", "loading finised");
        handler.hideProgress();
    }
}