Category Archives: Android

Android Custom EditText with line numbers

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.

  1. Extend EditText, implement one constructor and prepare the only overdrawn method, onDraw()
  2. 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.
  3. We just declare the Paint and Rect we will use.
  4. We then provide Getter/Setter for these properties. But we did not provide any for LINE_NUMBER_TEXTSIZE_GAP. we do not want it to change, however, we allow the class that will extend this one to change. We do so by applying protected modifier.
  5. Next we need to initialize some variables inside the constructor. Paint and Rect are initialized.
  6. Now, the most important phase.

  • 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.