Search code examples
android-studiowebviewnavigationnavigation-drawer

Open link in WebView when tapping a navigation drawer item


Followed a tutorial here to create a navigation drawer and worked fine. The webview also loads when the app starts.

My Landing page loads when the app starts:

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

    myWebView = findViewById(R.id.activity_main_webview);
    WebSettings webSettings = myWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    myWebView.setWebChromeClient(new WebChromeClient());
    myWebView.loadUrl("http://192.168.43.105/public_html/central/updates.php");
    myWebView.setWebViewClient(new WebViewClient());}

Url should open when a navigation item was selected:

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.nav_search) {
            myWebView.loadUrl("http://192.168.43.105/public_html/central/search.php");
            return true;
        }
        if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
              //return super.onOptionsItemSelected(item);
        }
        return super.onOptionsItemSelected(item);
    }

Drawer Items is located at res>menu>navigation_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools"
      tools:ignore="HardcodedText">

      <item
         android:id="@+id/nav_search"
         android:title="Search" />
</menu>

Tried:

String url = "http://192.168.43.105/public_html/central/search.php";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);

And followed this from developer.android.com:

    switch (item.getItemId()) {
    case R.id.nav_search:
    String url="http://192.168.43.105/public_html/central/search.php";
        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.loadUrl(url);
        return true;
    default:
        return super.onOptionsItemSelected(item);
}

I didn't get any error when starting the app. Any help would be greatly appreciated!


Solution

  • For external URL try this:

    Uri uri = Uri.parse("https://www.google.com");
    startActivity(new Intent(Intent.ACTION_VIEW, uri));
    

    If you want to web browser open in your activity try this:

    WebView webView = (WebView) findViewById(R.id.webView1);
    WebSettings settings = webview.getSettings();
    settings.setJavaScriptEnabled(true);
    webView.loadUrl(URL);
    

    and If you want to use the zoom control in your browser then add this also:

    settings.setSupportZoom(true);
    settings.setBuiltInZoomControls(true);