如何高亮显示用户在EditText中选择的特定单词。例如,我有一个EditText,其中用户输入句子“你好,你好吗?”,现在用户可以选择单词Like this Image。而且我必须在TextView上的整个句子中显示所选单词。
答案 0 :(得分:1)
您可以使用replace()方法,然后使用Html.fromHtml(),如下所示
yourEditText.setOnFocusChangedListener(new OnFocusChangedListener(){
@Override
public void onFocusChange(View v, boolean hasFocus){
if (hasFocus){
if (str.contains("Hello how are you ?") == true)
{
str = ((EditText)v)getText.ToString().replaceAll("Hello how are you ?", "<font color='red'>Hello how are you ?</font>");
((EditText)v).setText(Html.fromHtml(str), TextView.BufferType.SPANNABLE);
}
}
}
});
[编辑1]
yourEditText.setOnFocusChangedListener(new OnFocusChangedListener(){
@Override
public void onFocusChange(View v, boolean hasFocus){
if (hasFocus){
// But the words in an ArrayList then use them
for(String s : arrLst){
if (str.contains(s) == true) {
str = ((EditText)v)getText.ToString().replaceAll(s, "<font color='red'>Hello how are you ?</font>");
((EditText)v).setText(Html.fromHtml(str), TextView.BufferType.SPANNABLE); }
}
}
}
});
[编辑2]
yourEditText.setOnFocusChangedListener(new OnFocusChangedListener(){
@Override
public void onFocusChange(View v, boolean hasFocus){
if (hasFocus){
int sSelection = ((EditText)v)getText.ToString().getSelectionStart();
int eSelection = ((EditText)v)getText.ToString().getSelectionEnd();
String sString = string.substring(sSelection, eSelection);
str = ((EditText)v)getText.ToString().replaceAll(sString , "<font color='red'>"+sString +"</font>");
((EditText)v).setText(Html.fromHtml(str), TextView.BufferType.SPANNABLE);
}
}
});
答案 1 :(得分:1)
试试这可能会帮助你。
"android:textColorHighlight="#00f000"
答案 2 :(得分:1)
您可以使用spannable
实现这一目标看看EditText
有一个api可以获得选择:Selection in EditText
您可以使用TextView
SpannableString
中设置多色文字
所以在这样的代码中结合两者:
edit.setOnEditorActionListener(
new EditText.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH ||
actionId == EditorInfo.IME_ACTION_DONE ||
event.getAction() == KeyEvent.ACTION_DOWN &&
event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
if (!event.isShiftPressed()) {
// the user is done typing.
//edit is the EditText
Spannable spann = new SpannableString(edit.getText());
spann.setSpan(new ForegroundColorSpan(Color.BLUE), edit.getSelectionStart(), edit.getSelectionEnd(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spann); // TextView
return true; // consume.
}
}
return false; // pass on to other listeners.
}
});
应该给你想要的效果
结束编辑检测代码来自此处:SO Answer
答案 3 :(得分:0)
使用这样的html:
Spanned s = Html.fromHtml(string.replace(selectedString, "<font color=\"red\">" + selectedString + "</font>"));
edittext.text(s);