如何在Android中突出显示Html标签内的选定字符串?

时间:2014-01-31 11:33:44

标签: android html css string highlight

我有带有字符串的html标签。我想使用搜索按钮点击搜索字符串。我搜索了Html标签中的单词contains.But我需要的是,我想突出显示搜索到的文本字符串。但它不会来。我只使用字体颜色。因此文字颜色只会改变。

我的代码是,

text=(TextView) findViewById(R.id.text);
      ss="<h1>Soins palliatifs pluridisciplinaires chez un malade en fin de vie." +
            " Accompagnement d'un mourrant et de son entourage</h1><p>&nbsp;</p><p>&nbsp;</p>";

             text.setText(Html.fromHtml(ss));

     et = (EditText) findViewById(R.id.textView1);
     search= (Button) findViewById(R.id.button);

     search.setOnClickListener(new OnClickListener() {

         public void onClick(View v) {
             // TODO Auto-generated method stub

             text.setText(ss);
             String ett =et.getText().toString();
             String tvt =text.getText().toString();

             String  origString = ss.replaceAll(ett,"<font color='yellow'>"+ett+"</font>");
             text.setText(Html.fromHtml(origString));

//             int ofe = tvt.indexOf(ett,0);   
//             SpannableString WordtoSpan = new SpannableString( text.getText() );
//
//     for(int ofs=0;ofs<tvt.length() && ofe!=-1;ofs=ofe+1)
//     {       
//       ofe = tvt.indexOf(ett,ofs);   
//               if(ofe == -1)
//                   break;
//               else
//                   {                       
//
//                   WordtoSpan.setSpan(new BackgroundColorSpan(0xFFFFFF00), ofe, ofe+ett.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//                  String sss=WordtoSpan.toString();
////                   text.setText(Html.fromHtml(sss), TextView.BufferType.SPANNABLE);
//                   text.setText(WordtoSpan, TextView.BufferType.SPANNABLE);
//                   
//                   }
//
//        }  


         }
     });

    }

任何人都可以帮我突出字符串吗?

1 个答案:

答案 0 :(得分:0)

使用以下代码

TextView textView = (TextView)findViewById(R.id.text);
    String ss="<h1>Soins palliatifs pluridisciplinaires chez un malade en fin de vie." +
            " Accompagnement d'un mourrant et de son entourage</h1><p>&nbsp;</p><p>&nbsp;</p>";

    Spannable WordtoSpan = new SpannableString(Html.fromHtml(ss));        
    WordtoSpan.setSpan(new BackgroundColorSpan(Color.BLUE), 5, 15, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    textView.setText(WordtoSpan);

其中5是文本的起始索引,15是最后一个索引。根据您的要求更改颜色。