在android中使用WebView了解onBackPressed方法

时间:2017-01-05 17:25:19

标签: android android-webview onbackpressed

有人帮我理解。我正在使用android studio构建一个简单的WebView应用程序,并使用覆盖方法onBackPressed()来使功能在有人触摸后退按钮时返回。不幸的是我的应用程序关闭错误“应用程序已停止工作”同时android studio也显示一些运行时错误。我的代码如下: - 这两点都不起作用:

@Override
public void onBackPressed() 
{
    if (view.canGoBack())
    {
        view.goBack();
    } else
    {
        //otherwise exit my app
        super.onBackPressed();
    }
}

这也不奏效:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
    view.goBack();
    return true;
}

return super.onKeyDown(keyCode, event);
}

我不知道出了什么问题,请有人清楚我的观点。

更新:当我在模拟器中运行我的应用程序时,它工作正常,但是当我点击我的设备上的后退按钮时,它应该返回到上一页,而不是它停止工作中的错误设备出来“很遗憾,appname已停止工作“并且android studio中的错误消息如下: -

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: pk.shippingexpress.shippingexpress, PID: 1996
              java.lang.NullPointerException
                  at pk.shippingexpress.shippingexpress.MainActivity.onBackPressed(MainActivity.java:42)
                  at android.app.Activity.onKeyUp(Activity.java:2193)
                  at android.view.KeyEvent.dispatch(KeyEvent.java:2664)
                  at android.app.Activity.dispatchKeyEvent(Activity.java:2423)
                  at android.support.v7.app.AppCompatActivity.dispatchKeyEvent(AppCompatActivity.java:547)
                  at android.support.v7.view.WindowCallbackWrapper.dispatchKeyEvent(WindowCallbackWrapper.java:59)
                  at android.support.v7.app.AppCompatDelegateImplBase$AppCompatWindowCallbackBase.dispatchKeyEvent(AppCompatDelegateImplBase.java:319)
                  at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1962)
                  at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:3852)
                  at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3826)
                  at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3399)
                  at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3449)
                  at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3418)
                  at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3525)
                  at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3426)
                  at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3582)
                  at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3399)
                  at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3449)
                  at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3418)
                  at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3426)
                  at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3399)
                  at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3449)
                  at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3418)
                  at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3558)
                  at android.view.ViewRootImpl$ImeInputStage.onFinishedInputEvent(ViewRootImpl.java:3718)
                  at android.view.inputmethod.InputMethodManager$PendingEvent.run(InputMethodManager.java:2010)
                  at android.view.inputmethod.InputMethodManager.invokeFinishedInputEventCallback(InputMethodManager.java:1704)
                  at android.view.inputmethod.InputMethodManager.finishedInputEvent(InputMethodManager.java:1695)
                  at android.view.inputmethod.InputMethodManager$ImeInputEventSender.onInputEventFinished(InputMethodManager.java:1987)
                  at android.view.InputEventSender.dispatchInputEventFinished(InputEventSender.java:141)
                  at android.os.MessageQueue.nativePollOnce(Native Method)
                  at android.os.MessageQueue.next(MessageQueue.java:138)
                  at android.os.Looper.loop(Looper.java:123)
                  at android.app.ActivityThread.main(ActivityThread.java:5017)
                  at java.lang.reflect.Method.invokeNative(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:515)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
                  at dalvik.system.NativeStart.main(Native Method) 

我的MainActivity.java的完整代码如下: -

package pk.shippingexpress.shippingexpress;

import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;

public class MainActivity extends AppCompatActivity {

    public WebView view;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String url = "http://easyonlineconverter.com";
        WebView view = (WebView) this.findViewById(R.id.express);
        view.getSettings().setJavaScriptEnabled(true);
        view.loadUrl(url);
        view.setWebViewClient(new WebViewClient());

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }
    @Override
public void onBackPressed() 
{
    if (view.canGoBack())
    {
        view.goBack();
    } else 

    {
        //otherwise exit my app
        super.onBackPressed();
    }
}


    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("Main Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(client, getIndexApiAction());
        client.disconnect();
    }
}

2 个答案:

答案 0 :(得分:0)

java.lang.NullPointerException
                  at pk.shippingexpress.shippingexpress.MainActivity.onBackPressed(MainActivity.java:42)

再次检查此行中的内容。我使用完全相同的代码,没有任何问题。

@Override
public void onBackPressed() {
    if (webView.canGoBack()) {
        webView.goBack();
    } else {
        super.onBackPressed();
    }
}

答案 1 :(得分:0)

首先声明一个类变量:

    public WebView view;

然后你初始化一个无意中影响类变量的局部变量:

    WebView view = (WebView) this.findViewById(R.id.express);

这样当你到达这一行时

    if (view.canGoBack())

view为空。

将其他行更改为

    view = (WebView) this.findViewById(R.id.express);

以获得正确的操作。