Sometimes you could be wandering how to have an edittext with numbered lines, just like most code editors.
Be assured that things ate easier than you think.
In this tutorial, I will show you how you can implement. We’ll name our custom EditText LineNumberedEditText.
- Extend EditText, implement one constructor and prepare the only overdrawn method, onDraw()
Decide the complementary properties
- We need to be able to show or hide the numbers, so we set a flag:
- There should be a margin gap between the rightmost number margin and the left margin of the text. This gap is temporarily set to 2.
- The font size of the number should be smaller than that of the actuall text. We set it 2 sizes less.
- onDraw() will actually do the drawing.
- the drawing is done only if the user choses to show line numbers.
- next we adjust the font size of the line number in case the user decided to change the size of his text.
- we get the base line, the y position at which the number will be drawn.
- we prepare the String t variable will contain the number to draw an it will help calculate the width of the line text.
- the for…loop will enable the canvas to draw the numbers on each line. the number of lines is determined by getCount(), the y coordinate of the new line is determined by adding the line height to the base line.
- after all the line numbers are drawn, we have to readjust the padding of the actual text. We will keep the 3 paddings, but we have to modify the left padding. the left padding will be equal to the width of the last line number printed + lineNumberMarginGap.
- finally, we call super to draw the actual text on top of the line numbers layer.
the full code can be found here.
This is the snapshot of its implementation.