当用户输入EditText时,我希望某些关键字能够改变颜色。 当应用程序发现用户输入HTML并使用Html.fromHtml时,我可以在关键字周围放置HTML标签,但用户将自己输入真正的HTML标签,这会弄乱它。所以我想我应该使用Spannable?
我应该如何扫描这些关键字的EditText?意义 - 什么是最有效的方式?我想的可能是所有关键字的数组 - 然后循环查看是否找到任何匹配项。关于如何处理这个的任何想法?
答案 0 :(得分:2)
您可以在EditText上使用TextWatcher查看用户正在键入的内容,并使用Linkify检查模式。 https://developer.android.com/reference/android/text/util/Linkify.html
EditText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
}
使用onTextChanged Listener检查用户输入的内容。
模式匹配示例.. int flags = Pattern.CASE_INSENSITIVE; 模式p = Pattern.compile(“\ [0-9] * \”,flags); Linkify.addLinks(myTextView,p, “内容://com.foo”);
答案 1 :(得分:0)
创建模式匹配器并将模式与onTextChanged Listener中的Text匹配
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.util.Log;
import android.widget.EditText;
public class ColorEditText extends Activity {
private Pattern helloPattern = Pattern.compile("Hello");
private Pattern simplePattern = Pattern.compile("Simple");
private SpannableStringBuilder spannable;
private EditText edit;
private TextWatcher colorChangeText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_color_edit_text);
edit =(EditText) findViewById(R.id.edit);
colorChangeText = new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
edit.removeTextChangedListener(colorChangeText);
Log.d("Changes",edit.getText().toString());
spannable = new SpannableStringBuilder( edit.getText().toString() );
Matcher o = helloPattern.matcher(spannable);
while (o.find()) {
spannable.setSpan(new StyleSpan(Typeface.BOLD), o.start(), o.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.setSpan(new ForegroundColorSpan(Color.rgb(103, 58, 183)), o.start(), o.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
Matcher n = simplePattern.matcher(spannable);
while (n.find()) {
spannable.setSpan(new StyleSpan(Typeface.BOLD), n.start(), n.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.setSpan(new ForegroundColorSpan(Color.rgb(0, 105, 92)), n.start(), n.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
edit.setText(spannable);
edit.setSelection(spannable.length());
edit.addTextChangedListener(colorChangeText);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
};
edit.addTextChangedListener(colorChangeText);
}
}