使文本在列表视图上加粗以动态指定单词 [英] Making text bold on a listview to a specify word dynamically

查看:91
本文介绍了使文本在列表视图上加粗以动态指定单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在与ArrayList项目/值中的句子中的单词匹配的单词上添加颜色和粗体.到目前为止,我所做的如下...因此,我有一个名为filter"Hello"的String变量,现在我想遍历ArrayList itemList并从ArrayList项目中找到"Hello"并将其变为粗体和蓝色.

I am trying to put color and bold up on a word that matches the word from a sentence in ArrayList items/value. what I have done so far is as below... so I have a String variable called filter "Hello" now I want to iterate through ArrayList itemList and find "Hello" from ArrayList items and make it bold and blue.

String filter = "Hello";
    String itemValue = "I just want to say Hello world! Hello";

    itemList = new ArrayList<String>();
    for(int i = 0; i<10; i++)
    {
        itemList.add("I just want to say Hello world! Hello");
    }
    sentence = new ArrayList<String>();
    for(int j=0; j<itemList.size(); j++)
    {
        int startPos = itemList.get(j).toString().toLowerCase(Locale.US).indexOf(filter.toLowerCase(Locale.US));
        int endPos = startPos + filter.length();

        if (startPos != -1) // This should always be true, just a sanity check
        {
            Spannable spannable = new SpannableString(itemValue);
            ColorStateList blueColor = new ColorStateList(new int[][] { new int[] {}}, new int[] { Color.BLUE });
            TextAppearanceSpan highlightSpan = new TextAppearanceSpan(null, Typeface.BOLD, -1, blueColor, null);

            spannable.setSpan(highlightSpan, startPos, endPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            tv.setText(spannable);

            sentence.add(itemValue);

            ListView lv = (ListView)findViewById(R.id.listView1);
            //ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
              //      android.R.layout.simple_list_item_1, android.R.id.text1, sentence);
            MyPerformanceArrayAdapter adapter = new MyPerformanceArrayAdapter(this, spannable, counterArrayList);
            lv.setAdapter(adapter);
        }
        else
            tv.setText(itemValue);                 
    }             

它无法正常工作,请您帮我

its not working can you please help me

推荐答案

您应该让另一个构造函数向其传递另一个参数字符串过滤器,该字符串将包含以粗体显示的字符串.

You should make another constructor passing it another argument String filter which will contain your string to be bold.

将其分配给 arrayAdapter

现在,在显示视图时,您应该在每个句子中替换 filter .即 sentence.replace(filter,< b>" + filter +</b>")

Now while displaying the view, You should replace the filter in every sentence. i.e. sentence.replace(filter, "<b>" + filter + "</b>")

并将其显示在textView中,如下所示: myTextView.setText(Html.fromHtml(sentence));

And show it into the textView like this myTextView.setText(Html.fromHtml(sentence));

之后,您要做的就是重置适配器

这篇关于使文本在列表视图上加粗以动态指定单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆