android 应用操作栏中的刷新按钮

Refresh button in action bar of android app

我是 android 应用程序的新手。我正在尝试执行一个应在操作栏中包含刷新按钮的应用程序。编译代码时,工作室提示这个错误

"Error:(50, 20) error: non-static method reload() cannot be referenced from a static context"

我写到现在

import android.os.Bundle;
import android.webkit.WebView;
import android.widget.Toast;
import android.webkit.WebViewClient;
import android.app.Activity;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Menu;


public class MainActivity extends Activity {

private WebView mWebView;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mWebView = new WebView(this);
    mWebView.getSettings().setJavaScriptEnabled(true);
    final Activity activity = this;
    mWebView.setWebViewClient(new WebViewClient(){

        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
        }

    });

    mWebView.loadUrl("http://www.example.com");
    setContentView(mWebView);

}

@Override
public boolean onCreateOptionsMenu (Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_main, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if(item.getItemId() == R.id.action_refresh){
        WebView.reload();
        return true;
    }
    return super.onOptionsItemSelected(item);
 }
}

menu_main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"      tools:context=".MainActivity">
<item android:id="@+id/action_settings" android:title="@string/action_settings"
    android:orderInCategory="100" app:showAsAction="never" />

 <item
    android:id="@+id/action_refresh"
    android:title="@string/refresh_button"
    android:icon="@drawable/ic_action_refresh"
    android:orderInCategory="1"
    app:showAsAction="never"
    />

</menu>

WebView.reload()更改为mWebView.reload()

在前一种情况下,您是在 WebView class 上调用 reload(),而在后一种情况下,您是在告诉您具体的要重新加载 WebView 的实例。

This SO question 可能会更清楚一点。