[英]Hyperlink click in WebView within fragment should open in new WebView in activity (tricky)
我在 WebView 中使用片段。 Webview 正確打開。 我的意圖如下:訪問者單擊 Fragment 內 WebView 中的任何鏈接。 單擊的鏈接在新活動中的新 WebView 中打開。 棘手的部分 - 所有鏈接都來自同一個網站,沒有外部鏈接。 至少對我來說很棘手。 非常感謝您的幫助! :)
這是我來自 Fragment 的 WebView 代碼:
public class HomeFragment extends Fragment {
@SuppressLint("SetJavaScriptEnabled")
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_naslovna, container, false);
WebView webView = view.findViewById(R.id.webView1);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("https://mywebpage.com/");
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
return view;
}
}
請試試這個:
WebViewClient webClient = new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
if( url.equals("http://test.com") ){
// do whatever you want e.g. open up activity with web view and pass the url
}
return true;
}
}
拼圖工作又花了 6 個小時,但這就是最后修復的方式。
public class HomeFragment extends Fragment {
WebView webView;
SwipeRefreshLayout swipeToRefreshLayout;
@SuppressLint("SetJavaScriptEnabled")
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_naslovna, container, false);
webView = view.findViewById(R.id.webView1);
final String pageUrl = "https://mywebpage.com/";
swipeToRefreshLayout = (SwipeRefreshLayout)view.findViewById(R.id.swiperefresh);
swipeToRefreshLayout.setOnRefreshListener(new RtvTkSwipeToRefreshListener(webView, swipeToRefreshLayout));
webView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url != pageUrl) {
startNewActivity(url);
}
return true;
}
});
webView.loadUrl(pageUrl);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
return view;
}
private void startNewActivity(String url) {
Intent myIntent = new Intent(getActivity(), NewActivity.class);
myIntent.putExtra("url", url);
getActivity().startActivity(myIntent);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.