我正在 Android 中制作一个文本编辑器,我想向它添加语法高亮。在我当前的实现中,当我输入一些东西时,UI 很迟钝。我需要帮助来优化我当前的实现。
private void onEditorListener() {
edtEditor.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
if (timer != null) {
timer.cancel();
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
@Override
public void afterTextChanged(final Editable s) {
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
// do your actual work here
MaineActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
}
});
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
MaineActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
textHighLighter(s);
}
});
}
}, 600);
}
});
}
private void textHighLighter(Editable s) {
// Check the matcher for general keywords..
Matcher a = Patterns.GENERAL_KEYWORDS.matcher(s.toString());
// Check the matcher for html tags..
Matcher b = Patterns.HTML_TAGS.matcher(s.toString());
// Check the matcher for html attribute..
Matcher c = Patterns.HTML_ATTRS.matcher(s.toString());
// Check the matcher for symbol..
Matcher d = Patterns.SYMBOLS.matcher(s.toString());
// Check the matcher for general strings..
Matcher e = Patterns.GENERAL_STRINGS.matcher(s.toString());
// Find all the general key words and change the text color...
// Find all the html tags words and change the text color...
while (b.find()) {
s.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.orchid)), b.start(), b.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//android.util.Log.i("VINCE", b.toString());
}
while (a.find()) {
s.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.bounded)), a.start(), a.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//android.util.Log.i("VINCE", b.toString());
}
while (c.find()) {
s.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.henn)), c.start(), c.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//android.util.Log.i("VINCE", b.toString());
}
while (d.find()) {
s.setSpan(new ForegroundColorSpan(Color.WHITE), d.start(), d.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//android.util.Log.i("VINCE", b.toString());
}
while (e.find()) {
s.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.general_str)), e.start(), e.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//android.util.Log.i("VINCE", b.toString());
}
}