我正在使用模块从编辑文本中搜索抓取文本并将其搜索到当前文本视图中。如果存在则在当前文本视图中突出显示该文本我也搜索了这段代码,但没有找到任何相关的答案。
tv=(TextView) mView.findViewById(R.id.detailsText);
edit_text=(EditText)findViewById(R.id.searchText);
edit_text.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
hightLightText(tv, s.toString());
}
});
}
void hightLightText(TextView textView, String searchString){
try{
String s=getResources().getString(R.string.firstpage);
String withHighLightedText = s.replaceAll(searchString, "<font color='red'>"+searchString+"</font>");
String styledText = "This is <font color='red'>simple</font>.";
textView.setText(Html.fromHtml(withHighLightedText), TextView.BufferType.SPANNABLE);
}catch(Exception ex){
}
}
答案 0 :(得分:2)
TextView
内的HTML代码格式非常有限。
<b>Bold</b> and <i>Italic</i>
干活,但是
<font color>
遗憾的是没有。
使用Spannable来突出显示您想要的部分文字。
以下是在EditText
视图中制作选定文字斜体的示例:Is there any example about Spanned and Spannable text
答案 1 :(得分:1)
调用以下功能突出显示。
public void hightLightText(TextView textView, String searchString) {
String s = textView.getText().toString();
SpannableString str = new SpannableString(s);
if (searchString != null && !searchString.equalsIgnoreCase("")) {
int startIndex = 0;
while (true) {
startIndex = s.indexOf(searchString, startIndex);
if (startIndex >= 0) {
str.setSpan(new BackgroundColorSpan(Color.YELLOW),
startIndex, startIndex + searchString.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
startIndex++;
} else {
break;
}
}
}
textView.setText(str);
}
答案 2 :(得分:0)
EditText edit_text;
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edittest);
tv=(TextView) findViewById(R.id.detailsText);
edit_text=(EditText)findViewById(R.id.searchText);
edit_text.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
hightLightText(tv, edit_text.getText().toString().trim());
}
});
}
void hightLightText(TextView textView, String searchString){
try{
String s=getResources().getString(R.string.app_name);
String withHighLightedText = s.replaceAll(searchString, "<font color='red'>"+searchString+"</font>");
String styledText = "This is <font color='red'>simple</font>.";
textView.setText(Html.fromHtml(withHighLightedText), TextView.BufferType.SPANNABLE);
}catch(Exception ex){
}
}
在您的代码中只需更改波纹管方法
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
hightLightText(tv, edit_text.getText().toString().trim());
}