-1

I just wanted to open a second activity (webview) when user click on links whitch ends like .html. MainActivity, and SecondActivity are the same

Code looks as follow:

if (url.endsWith(".html")) {
            try {
                view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            } catch (Exception e) {
                // error
            }

            return true;
        }

Of course this opens the content into webbrowser outside the app. Can you please help me in this?

1 Answers1

0

First of all add this to your manifest

 <uses-permission android:name="android.permission.INTERNET"/>

And add this activity as well

  <activity android:name=".WebViewClientDemoActivity"/>

Now in your mainActivity you create intent like this

startActivity(new Intent(this, WebViewClientDemoActivity.class));

Now create this class

 public class WebViewClientDemoActivity extends Activity {

WebView web;
@Override @SuppressLint("SetJavaScriptEnabled")
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    web =  findViewById(R.id.web_view);
    web.setWebViewClient(new myWebClient());
    web.getSettings().setJavaScriptEnabled(true);
    
    //for example i used this web page
    web.loadUrl("https://stackoverflow.com/questions/69032318/java-android-open-secondactivity-when-url-endswith-html-webview");
}

public static class myWebClient extends WebViewClient{
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon){
        super.onPageStarted(view, url, favicon);
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url){
        view.loadUrl(url);
        return true;
    }
}

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

By the way there is a probelm using the emulator with webview you can use your phone or you can see this solution

Yechiel babani
  • 344
  • 3
  • 13