11

您好,我想知道如何突出显示在 EditText 中输入并将出现在 TextView 中的所有单词,这篇文章与这篇文章有关Highlight Textview Using EditText

4

2 回答 2

21

et 是您的 EditText 并且tv是 TextView 对象。使用以下代码:


public class MotivationalQuotesActivity extends Activity {
    /** Called when the activity is first created. */

Button next;
EditText et; 
TextView tv;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
   et = (EditText) findViewById(R.id.et);
   tv = (TextView) findViewById(R.id.tv);
   tv.setText("The name of our country is Bangladesh. Bangladesh is a land of rivers.");

   next = (Button) findViewById(R.id.button1);
    next.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                tv.setText("The name of our country is Bangladesh. Bangladesh is a land of rivers.");
                String ett =et.getText().toString();
                String tvt =tv.getText().toString();

                int ofe = tvt.indexOf(ett,0);   
                Spannable WordtoSpan = new SpannableString( tv.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);
                      tv.setText(WordtoSpan, TextView.BufferType.SPANNABLE);
                      }


        }  


            }
        });

    }

}

结果是:

在此处输入图像描述

于 2012-05-29T13:35:51.833 回答
0

突出显示文本的一种简单快捷的方法是使用字符串替换方法。用字体标签替换期望字符串

Spanned strHTML= Html.fromHtml("<center>"+full_string.replaceAll(strSrch,"<font color='yellow'>"+strSrch+"</font>")+"</center><br/>");
TextView tv=(TextView) v.findViewById(R.id.txtPager);
tv.setText(strHTML,TextView.BufferType.SPANNABLE);
于 2017-12-02T06:37:19.903 回答