【发布时间】:2012-06-03 17:04:01
【问题描述】:
您好,我想知道如何突出显示在 EditText 中输入并将出现在 TextView 中的所有 Words 这篇文章与此相关Highlight Textview Using EditText
【问题讨论】:
标签: android textview android-edittext highlight
您好,我想知道如何突出显示在 EditText 中输入并将出现在 TextView 中的所有 Words 这篇文章与此相关Highlight Textview Using EditText
【问题讨论】:
标签: android textview android-edittext highlight
说 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);
}
}
}
});
}
}
结果是:
【讨论】:
tv.setText("The name of our country is Bangladesh. Bangladesh is a land of rivers."); 第二:使用上述突出显示的方法,但使用背景的颜色(在本例中为 黑色)作为突出显示的颜色,如:WordtoSpan.setSpan(new BackgroundColorSpan(color.black), ofe, ofe+ett.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
突出显示文本的一种简单快捷的方法是使用字符串替换方法。用字体标签替换想要的字符串
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);
【讨论】: