如何突出显示textview中包含的部分文本?

时间:2015-03-08 13:58:23

标签: java android textview highlight

如果可能,我如何突出显示textview中包含的部分文本并将其检索回代码以供其他用途?

2 个答案:

答案 0 :(得分:1)

您可以使用以下方法将多个样式应用于Textview中的字符串:

TextView textView = (TextView) findViewById(R.id.tvText);
String strFirst = "Text1";
String strSecond = "Text2";
Spannable spanTxt = new SpannableString(strFirst+strSecond);

//将自定义字体设置为跨越spannable对象的一部分

spanTxt.setSpan( new CustomTypefaceSpan("sans-serif",CUSTOM_TYPEFACE),0, strFirst.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spanTxt.setSpan(new CustomTypefaceSpan("sansserif",SECOND_CUSTOM_TYPEFACE), strFirst.length(), strFirst.length() + strSecond.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

//使用spannable对象

设置textView的文本
textView.setText( spanTxt );

享受!

答案 1 :(得分:1)

我终于通过使用WebView结合Jquery移动插件方法swipe和Java JavascriptInteface来实现我想要做的事情:

首先,我将此html文件放在项目的assets文件夹中,以便我可以在WebView中加载它:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Reader</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script>
    function addWords(val) {
        if (val != " ")
            $("#cont").append("<span>" + val + "</span>");
        else
            $("#cont").append("&nbsp;");
    }
</script>
<style>
    html,
    body {
        padding: 0;
        margin: 0;
    }

    div.box {
        width: 30em;
        height: 3em;
        background-color: #108040;
    }

    .swipe {
        background-color: #F0A90F;
    }

    #cont {
        display: inline-block;
        margin: 5px;
        word-wrap: break-word;
    }

    span {
        word-wrap: break-word;
    }
</style>
</head>

<body>
<div id="cont">
</div>

<script>
    $(function() {
        // Bind the swipeHandler callback function to the swipe event on div.box
        $("div#cont").on("swipe", swipeHandler);

        // Callback function references the event target and adds the 'swipe' class to it
        function swipeHandler(event) {
            if ($(event.target).prop("tagName") != "DIV") {
                $(event.target).addClass("swipe");
                window.INTERFACE.getHighlightedText($(event.target).text());
            }
        }
    });
</script>

</body>

</html>    

从RSS提要链接获取完整文章文本后,我将文章中的所有单词追加到div#cont,将它们放在span标记中:

if(isOnline()){
        showCustomProgressDialog();
        WebView wb=(WebView)findViewById(R.id.webViewReader);
        RelativeLayout parent=(RelativeLayout)wb.getParent();
        parent.setVisibility(View.VISIBLE);
        wb.getSettings().setJavaScriptEnabled(true);
        wb.getSettings().setDomStorageEnabled(true);
        wb.addJavascriptInterface(theInterface, "INTERFACE");
        wb.getSettings().setJavaScriptCanOpenWindowsAutomatically(false);
        wb.getSettings().setSupportMultipleWindows(true);
        wb.getSettings().setUserAgentString("Mozilla/5.0 (Windows NT 6.1: it-IT) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36");
        wb.loadUrl("file:///android_asset/index.html");
        wb.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                super.shouldOverrideUrlLoading(view,url);
                return false;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                try {
                    JSONObject root = new JSONObject(home.getStringFromFile(getFilesDir() + "/" + home.DASHBOARDJSONFILENAME));
                    JSONObject innerObj = root.getJSONObject("dashboard").getJSONObject("lastarticle");
                    innerObj=new parseArticleFromUrl().execute("https://www.readability.com/api/content/v1/parser?url="+innerObj.getString("link").replace("\\/", "/")+"&token=YOURTOKEN").get();
                    String a="Nothing found";
                    if(innerObj!=null){
                            String content = innerObj.getString("content");
                            if(content!=null){
                                Document doc=Jsoup.parse(content);
                                a=doc.text();
                            }
                    }
                    StringTokenizer tokens = new StringTokenizer(a, " ");
                    for(;tokens.hasMoreTokens();)
                    {
                        String curr_token=tokens.nextToken();
                        curr_token = curr_token.replaceAll("\"", "\\\\\"");
                        view.loadUrl("javascript:addWords('"+curr_token+"');");
                        view.loadUrl("javascript:addWords(' ');");
                    }
                    ldialog.dismiss();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
    }    

然后通过使用JavascriptInteface类,我得到了突出显示的单词的定义:

public class MyJavaScriptInterface
{
    private String strval;

    public MyJavaScriptInterface()
    {
        strval = null;
    }

    @SuppressWarnings("unused")

    @JavascriptInterface

    public void getHighlightedText(String hword)
    {
        if(!hword.isEmpty())
        {
            strval = hword;
            new getWordDefinition().execute("http://api.wordnik.com/v4/word.json/"+hword+"/definitions?limit=1&includeRelated=false&useCanonical=false&includeTags=false&api_key=a2a73e7b926c924fad7001ca3111acd55af2ffabf50eb4ae5");
        }
        else
            strval="";
    }

    public String returnHtml()
    {
        return strval;
    }
}    

Results Screen