ユーザーが EditText で選択した特定の単語をハイライトする方法。たとえば、ユーザーが「こんにちは、お元気ですか?」という文を入力する EditText が 1 つあります。これで、ユーザーはLike this Imageという単語を選択できます。そして、その選択した単語を TextView の文全体で強調表示して表示する必要があります。
質問する
1682 次
4 に答える
1
スパン可能を使用してそれを達成できます
EditText
Selection を取得するための API があることを見てみましょう: 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
于 2013-03-18T10:34:25.753 に答える
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);
}
}
});
于 2013-03-18T10:11:37.757 に答える
1
これを試してみてください。
"android:textColorHighlight="#00f000"
于 2013-03-18T10:21:55.253 に答える
0
次のように html を使用します。
Spanned s = Html.fromHtml(string.replace(selectedString, "<font color=\"red\">" + selectedString + "</font>"));
edittext.text(s);
于 2013-03-18T10:09:49.883 に答える