У меня есть реализация редактирования текста, чтобы показать номера строк, а также выделить текущую строку. Я думаю, что это требует дополнительной оптимизации, потому что, когда я прокручиваю текст редактирования примерно с 500 строками кода, он тормозит, но когда я комментирую код, прокрутка выполняется плавно.
Мне нужна помощь в оптимизации этого onDraw
метод, в котором я делаю все выше. Номера строк отображаются справа с настраиваемым разделителем, например
1|
...
10|
..
100|
..
public class NumberedEditText extends AppCompatEditText {
private Rect nRect;
private Rect nRect_;
private int nOffset;
private Paint nPaint;
private Paint nPaint_;
private boolean nShow;
private int nAlignment;
private char nSeparator;
private boolean nLineHlt;
public NumberedEditText (Context context, AttributeSet attrs) {
super (context, attrs);
nRect = new Rect ();
nRect_ = new Rect ();
nPaint = new Paint ();
nPaint_ = new Paint ();
nAlignment = NUMBER_ALIGNMENT_LEFT_SEP_LEFT;
nSeparator="|";
nLineHlt = true;
nShow = true;
nOffset = 2;
nPaint_.setColor (Color.parseColor ("#222222"));
nPaint.setColor (Color.LTGRAY);
nPaint.setStyle (Paint.Style.FILL);
nPaint.setTypeface (Typeface.MONOSPACE);
}
@Override
public void onDraw (Canvas canvas) {
// I use short variable names because i think
// they are executed much faster.
if (nShow) {
nPaint.setTextSize (getTextSize () - nOffset);
int bl = getBaseline ();
int lc = getLineCount ();
int lh = getLineHeight ();
// i use an array here for efficient
// random access to store the
// positions where the line numbers
// will be according to the number
// of lines
String lcs = Integer.toString (lc);
int nl = lcs.length ();
char[] ch = new char[nl + 1];
int cl = ch.length;
String s;
// i fill the array with spaces
// ready to be replaced with numbers
for (int i = 0; i < nl; i++)
ch [i] = 32;
// set the last character to the separator
ch [nl] = nSeparator;
// now i loop thru all the numbers
// replacing the characters in the array
// (with spaces) with numbers
// to form something like
// ' 1|'
// ' 10|'
// ' 100|'
for (int i = 1, j = cl - 2; i <= lc; i++, bl += lh) {
if (i == 10 || i == 100 || 1 == 1000 || i == 10000 || i == 100000)
j--;
s = Integer.toString (i);
if (j > -1)
s.getChars (0, s.length (), ch, j);
canvas.drawText (ch, 0, cl, nRect.left, bl, nPaint);
}
// now i set the padding and an
// additional margin
setPadding ((int) nPaint.measureText (lcs + "__"), getPaddingTop (), getPaddingRight (), getPaddingBottom ());
}
// this is to highlight the current line
Layout l = getLayout ();
if (nLineHlt && l != null) {
int ln = l.getLineForOffset (getSelectionStart ());
getLineBounds (ln, nRect_);
canvas.drawRect (nRect_, nPaint_);
}
super.onDraw (canvas);
}
}
```