您好,我想知道如何在EditText中输入的所有单词在TextView中高亮显示,这篇文章与此有关Highlight Textview Using EditText
假设 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);
}
}
}
});
}
}
结果是:
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);
tv.setText("我们国家的名字是孟加拉国。孟加拉国是一个多河流的土地。");
第二种:使用上面的高亮方法,但将背景颜色(在这种情况下为黑色)作为高亮颜色,例如:WordtoSpan.setSpan(new BackgroundColorSpan(color.black), ofe, ofe+ett.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
- Imran Rana