具有深层链接的WebView中的向后导航

时间:2019-01-06 09:46:51

标签: android webview deep-linking back

我想在WebView中打开一个深层链接。 WebView具有自己的(第二个)活动。要从WebView返回到MainActivity,我必须按两次BackButton。第一次按下后,将显示一个空白面。按下MainActivity一次后如何到达BackButton

主要活动

Intent in = new Intent(MainActivity.this, WebViewActivity.class);
in.putExtra(EXTRA_MESSAGE, "http://play.google.com/store/apps/details?id=de.bernd.schiebepuzzle");
startActivity(in);

第二活动

public class WebViewActivity extends AppCompatActivity {

    private WebView myWebView;  // Datenschutzerklärung anzeigen
    private WebViewClient myWebViewClient;

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

        myWebView = (WebView) findViewById(R.id.myWebView);

        Intent intent = getIntent();
        String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
        myWebView.loadUrl(message);

    } // ende onCreate
}

我尝试过的事情:

覆盖onKeyDown

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    //  https://developer.android.com/guide/webapps/webview#java
    Toast toast = Toast.makeText(getApplicationContext(), "onKeyDown", Toast.LENGTH_SHORT);
    toast.show();

    // Check if the key event was the Back button and if there's history
    if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
        myWebView.goBack();
        return true;
    }
    // If it wasn't the Back key or there's no web page history, bubble up to the default
    // system behavior (probably exit the activity)
    return super.onKeyDown(keyCode, event);
}

重写onBackPressed

//https://developer.android.com/training/implementing-navigation/temporal#java

@Override
public void onBackPressed() {

    Toast toast = Toast.makeText(getApplicationContext(), "onBackPressed", Toast.LENGTH_SHORT);
    toast.show();

    if (myWebView.canGoBack()) {
        myWebView.goBack();

        return;
    }
   // Otherwise defer to system default behavior.
    myWebView.goBack();

    super.onBackPressed();
}

清单中的父母活动

 <activity
        android:name=".WebViewActivity"
        android:parentActivityName="de.bernd.schiebepuzzle.MainActivity"></activity>

setWebViewClient

WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebViewClient(MyWebViewClient);

问题是,第一次按下onBackPressed不会调用onKeyDownBackButton。该事件未触发。 (在我的示例中,仅在第二按时才能看到Toast。)

非常感谢。

0 个答案:

没有答案