Рисование нескольких линий в тексте редактирования, например блокнот - PullRequest
6 голосов
/ 12 мая 2011

Я смотрел на образец блокнота в Android SDK, смотрите здесь: http://developer.android.com/resources/samples/NotePad/src/com/example/android/notepad/NoteEditor.html

Дело в том, что он рисует только текущую линию, на которой находится курсор, например http://cdn2.staztic.com/screenshots/simple-notepad-app-al-1.jpg

Но я хотел бы отобразить строки, которые заполняют экран, например http://www.itismyworld.info/wp-content/uploads/2010/03/AK-notebook.png

Любые предложения будут отличными.Соответствующий фрагмент кода, кажется, здесь:

    protected void onDraw(Canvas canvas) {

        // Gets the number of lines of text in the View.
        int count = getLineCount();

        // Gets the global Rect and Paint objects
        Rect r = mRect;
        Paint paint = mPaint;

        /*
         * Draws one line in the rectangle for every line of text in the EditText
         */
        for (int i = 0; i < count; i++) {

            // Gets the baseline coordinates for the current line of text
            int baseline = getLineBounds(i, r);

            /*
             * Draws a line in the background from the left of the rectangle to the right,
             * at a vertical position one dip below the baseline, using the "paint" object
             * for details.
             */
            canvas.drawLine(r.left, baseline + 1, r.right, baseline + 1, paint);
        }

        // Finishes up by calling the parent method
        super.onDraw(canvas);
    }

Ответы [ 4 ]

33 голосов
/ 24 мая 2011

Это код, основанный на предложении jkhouws1 и редакторе заметок Google

public class LinedEditText extends EditText {
    private Rect mRect;
    private Paint mPaint;

    // we need this constructor for LayoutInflater
    public LinedEditText(Context context, AttributeSet attrs) {
        super(context, attrs);

        mRect = new Rect();
        mPaint = new Paint();
        mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        mPaint.setColor(R.color.edit_note_line); //SET YOUR OWN COLOR HERE
    }

    @Override
    protected void onDraw(Canvas canvas) {
        //int count = getLineCount();

        int height = getHeight();
        int line_height = getLineHeight();

        int count = height / line_height;

        if (getLineCount() > count)
            count = getLineCount();//for long text with scrolling

        Rect r = mRect;
        Paint paint = mPaint;
        int baseline = getLineBounds(0, r);//first line

        for (int i = 0; i < count; i++) {

            canvas.drawLine(r.left, baseline + 1, r.right, baseline + 1, paint);
            baseline += getLineHeight();//next line
        }

        super.onDraw(canvas);
    }
}

В Eclipse IDE нажмите Ctrl + Shift + O, чтобы добавитьвесь необходимый импорт

4 голосов
/ 07 июня 2011

Я думаю, это то, что вам нужно:

public class LinedEditText extends EditText {

    private static Paint linePaint;

    static {
        linePaint = new Paint();
        linePaint.setColor(Color.BLACK);
        linePaint.setStyle(Style.STROKE);
    }

    public LinedEditText(Context context, AttributeSet attributes) {
        super(context, attributes);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Rect bounds = new Rect();
        int firstLineY = getLineBounds(0, bounds);
        int lineHeight = getLineHeight();
        int totalLines = Math.max(getLineCount(), getHeight() / lineHeight);

        for (int i = 0; i < totalLines; i++) {
            int lineY = firstLineY + i * lineHeight;
            canvas.drawLine(bounds.left, lineY, bounds.right, lineY, linePaint);
        }

        super.onDraw(canvas);
    }


}
2 голосов
/ 12 мая 2011

возможно, после этого для цикла вы рисуете * дополнительные линии.

getHeight () вернет высоту EditText в пикселях getLineHeight () будет высота одной стандартной строки

, поэтому getHeight / getlineHeight-getCount будет количеством оставшихся линий для рисования.

вы не можете использовать getLineBounds, используя вышеуказанные функции, вы можете вычислить положение оставшихся линий для рисования.

* По оценкам, поскольку форматирование текста может изменить высоту строки, но, поскольку в этих строках еще нет текста, это не должно вызывать проблем. Но по этой же причине вам следует только рисовать оставшиеся линии, а не использовать их для рисования всех линий.

0 голосов
/ 29 августа 2015
<com.example.goh2.pronoornotepad.LinedEditText
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="#ffffcc4b"
        android:gravity="top|left"
        android:singleLine="false"
        android:text=""
     />

Приведенный выше XML работает с кодом из ответа Max4ever :

   public class LinedEditText extends EditText {
    private Rect mRect;
    private Paint mPaint;

// we need this constructor for LayoutInflater
   public LinedEditText(Context context, AttributeSet attrs) {
    super(context, attrs);

    mRect = new Rect();
    mPaint = new Paint();
    mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
    mPaint.setColor(R.color.edit_note_line); //SET YOUR OWN COLOR HERE
}

@Override
protected void onDraw(Canvas canvas) {
    //int count = getLineCount();

    int height = getHeight();
    int line_height = getLineHeight();

    int count = height / line_height;

    if (getLineCount() > count)
        count = getLineCount();//for long text with scrolling

    Rect r = mRect;
    Paint paint = mPaint;
    int baseline = getLineBounds(0, r);//first line

    for (int i = 0; i < count; i++) {

        canvas.drawLine(r.left, baseline + 1, r.right, baseline + 1, paint);
        baseline += getLineHeight();//next line
    }

    super.onDraw(canvas);
    }
 }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...