【发布时间】:2018-10-22 18:47:32
【问题描述】:
我有一个带有 WebView 的片段活动,我希望在单击特定 url 时在其中打开或重定向到不同的片段。
注意:如果选择了不同于所需的 URL,它应该在同一个当前片段中打开。
【问题讨论】:
标签: android android-layout android-fragments android-intent
我有一个带有 WebView 的片段活动,我希望在单击特定 url 时在其中打开或重定向到不同的片段。
注意:如果选择了不同于所需的 URL,它应该在同一个当前片段中打开。
【问题讨论】:
标签: android android-layout android-fragments android-intent
您应该覆盖 url 加载。 使用如下内容:
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("your_url")) { //you can also use indexOf, equales etc.
// do what's needed
return true;
}
return false;
}
});
【讨论】:
在你为 webview 提供代码的 on-create 中添加这个(最好在 oncreate 方法的末尾添加)
webView.setWebViewClient(new MyWebViewClient());
然后在 oncreate 之外进行如下函数调用
private class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.equals("your url here")) {
Fragment newFragment = YourNewFrag();
// consider using Java coding conventions (upper first char class names!!!)
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container(usually a frame layout) view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
return true;
}
return false;
}
}
【讨论】: