如何在android中打开HTML字符串“ a href”到Webview

问题描述 投票:0回答:2

我如何打开仅在Webview上具有a href的html字符串,而不是在浏览器上打开?

我正在使用LinkMovementMethod,可以在其他应用程序(例如youtube的视频)上打开它,但是我有一些链接仅需要在webview上打开。

这是示例html字符串

String html_text =  "<h1>sample text</h1><p><small>February 1 1970</small></p><p class=\"text-center\"><img src=\"https://www.google.com\" /></p><p>sample (<a href=\"https://google.com\">here</a>).</p>"

我需要仅在Webview上打开a href。

这是我的代码

DetailActivity

public class DetailActivity extends AppCompatActivity implements Html.ImageGetter {

    private TextView newsContentTv;
    private WebView newsWebView;

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

        // add back arrow to toolbar
        if (getSupportActionBar() != null){
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }

        newsContentTv = (TextView) findViewById(R.id.textNewsContext);

        Intent i = getIntent();

        String news_content = i.getStringExtra("detail_content");

        Spanned spanned = Html.fromHtml(news_content, this, null);
        Spannable spannable = new SpannableString( Html.fromHtml(news_content) );
        newsContentTv.setText(spanned);

        newsContentTv.setMovementMethod(LinkMovementMethod.getInstance());

    }

任何帮助将不胜感激。

java android webview
2个回答
1
投票
// Create an unencoded HTML string
// then convert the unencoded HTML string into bytes, encode
// it with Base64, and load the data.
String html_text =
 "<h1>sample text</h1><p><small>February 1 1970</small></p><p class=\"text-center\"><img src=\"https://www.google.com\" /></p><p>sample (<a href=\"https://google.com\">here</a>).</p>";
String encodedHtml = Base64.encodeToString(html_text.getBytes(),
    Base64.NO_PADDING);
newsWebView.loadData(encodedHtml, "text/html", "base64");

希望对您有帮助。


0
投票
WebView webview = (WebView)this.findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadDataWithBaseURL("", data, "text/html", "UTF-8", "");
© www.soinside.com 2019 - 2024. All rights reserved.