【问题标题】:Force links to open in webview instead of a browser强制链接在 webview 而不是浏览器中打开
【发布时间】:2018-02-16 12:57:37
【问题描述】:

我是 Android 工作室的新手。

请检查我的代码

问题- 当我单击下面维护的任何活动时,它会在外部浏览器中打开,而不是在同一个 web 视图中加载。所以请建议我如何在同一个 webview 而不是浏览器中加载 url。

我添加了一些代码来停止打开外部浏览器,但它不能正常工作。

package com.hanumanbeniwal.www.hanumanbeniwal;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.KeyEvent;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;


import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;

import java.net.URI;

import static com.hanumanbeniwal.www.hanumanbeniwal.R.id.progressBar2;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    //initializing WebView
    private WebView mwebView;
    ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);



        AdView mAdView = (AdView) findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);
        //WebView
        mwebView = (WebView) findViewById(R.id.myWebView);
        WebSettings webSettings = mwebView.getSettings();



        //improve webView performance
        mwebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        mwebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        mwebView.getSettings().setAppCacheEnabled(true);
        mwebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        webSettings.setDomStorageEnabled(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSettings.setUseWideViewPort(true);
        webSettings.setSavePassword(true);
        webSettings.setSaveFormData(true);
        webSettings.setEnableSmoothTransition(true);
        mwebView.getSettings().setDomStorageEnabled(true);

        //force links open in webview only
        mwebView.setWebViewClient(new MyWebviewClient());
        webSettings.setJavaScriptEnabled(true);
        mwebView.loadUrl("http://www.hanumanbeniwal.com");

    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_home) {
            // Handle the camera action
            mwebView.loadUrl("http://www.hanumanbeniwal.com/home");
        } else if (id == R.id.nav_video) {
            mwebView.loadUrl("https://www.youtube.com/channel/UCoQcL7eGvx8462O3-Jef-Cg/");
        } else if (id == R.id.nav_news) {
            mwebView.loadUrl("https://m.facebook.com/hanumanbeniwal/");
        } else if (id == R.id.nav_images) {
            mwebView.loadUrl("https://m.facebook.com/hanumanbeniwal/photos/");
        } else if (id == R.id.nav_biography) {
            mwebView.loadUrl("http://www.hanumanbeniwal.com/home");
        }  else if (id == R.id.nav_contact) {
            mwebView.loadUrl("http://www.hanumanbeniwal.com/contact-us/");
        }
         else if (id == R.id.nav_complaint) {
            mwebView.loadUrl("http://www.google.com");
        } else if (id == R.id.nav_suggestion) {
            mwebView.loadUrl("http://www.google.com");
        }


        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    private class MyWebviewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (Uri.parse(url).getHost().equals("www.hanumanbeniwal.com")) {
                //open url contents in webview
                return false;
            } else {
                //here open external links in external browser or app
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(intent);
                return true;
            }

        }
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {

            super.onPageStarted(view, url, favicon);
            findViewById(R.id.progressBar2).setVisibility(View.VISIBLE);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            findViewById(R.id.progressBar2).setVisibility(View.GONE);
        }

    }
    //goto previous page when pressing back button

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            switch (keyCode) {
                case KeyEvent.KEYCODE_BACK:
                    if (mwebView.canGoBack()) {
                        mwebView.goBack();
                    } else
                    {
                        AlertDialog.Builder builder = new AlertDialog.Builder(this);
                        builder.setMessage("Are you sure you want to exit?")
                                .setCancelable(false)
                                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        finish();
                                    }
                                })
                                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        dialog.cancel();
                                    }
                                });
                        AlertDialog alert = builder.create();
                        alert.show();
                    }
                    return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}

【问题讨论】:

    标签: javascript android webview youtube


    【解决方案1】:

    您可以尝试将视频放在 iFrame 中,然后使用 loadData 方法代替 loadUrl

    String frameVideo = "<html><body>Video From YouTube<br><iframe width=\"420\" height=\"315\" src=\"https://www.youtube.com/channel/UCoQcL7eGvx8462O3-Jef-Cg\" frameborder=\"0\" allowfullscreen></iframe></body></html>";
    mwebView.loadData(frameVideo, "text/html", "utf-8");
    

    【讨论】:

      【解决方案2】:

      webView 内部:

       webview.apply{
      settings.javaScriptEnabled = true
      settings.loadWithOverviewMode = true
      settings.useWideViewPort = true
      webViewClient = MyClient()
      loadUrl("http://www.naver.com")
       }
      
      
      inner class MyClient : WebViewClient() {
          override fun shouldOverrideUrlLoading(view: WebView?, request: 
                 WebResourceRequest?): Boolean {
              view?.loadUrl(request?.url?.toString())
              return true
          }
      }
      

      这个答案是 @pistolcaffe 13 天前给我的,它非常有效,我希望这对你仍然有用。

      【讨论】:

        【解决方案3】:

        而不是

        if (Uri.parse(url).getHost().equals("www.hanumanbeniwal.com")) {
        

        尝试使用 contain 或 containsIgnoreCase

        if (Uri.parse(url).getHost().containsIgnoreCase("www.hanumanbeniwal.com")) {
        

        或者干脆

        if(url.containsIgnoreCase("www.hanumanbeniwal.com"))
        

        Intercept and override HTTP requests from WebView

        【讨论】:

        • 错误 - 无法解析符号 '' containsIganoreCase ''
        • 你拼错了ignore...你必须使用apache common lib...或者如果你不想这样做,如果你知道你的url将始终是小写的,那么将包含所有的字符串比 do contains 小写。take a look here
        猜你喜欢
        • 2014-05-15
        • 1970-01-01
        • 2011-12-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-02
        • 1970-01-01
        • 2020-04-25
        • 1970-01-01
        相关资源
        最近更新 更多