How to use ruled/horizontal lines to align text in

2019-02-19 13:07发布

Basically I want to do something like this in Android:

enter image description here

I am trying to draw horizontal lines in a custom EditText, and then typing on these lines.

I am using the text size for the distance between two horizontal lines. However, the size of cursor and that of text is not same. Hence, I am not able to maintain placing text "on" these lines.

The alignment of the text base to these horizontal lines are not coming as proper.

Here is the code used for drawing the lines:-

float textSize = getTextSize());
Paint paint = new Paint();
for (int i = 0; i < 50; i++) {
    canvas.drawLine(0, textSize * i, getWidth(), textSize * i, paint);
}

EditText doesn't privides has any method for getting the cursor size.

Kindly suggest if there is any workaround for this, or any other better way of doing this.

1条回答
啃猪蹄的小仙女
2楼-- · 2019-02-19 13:48

A custom EditText that draws lines between each line of text that is displayed:

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.STROKE);
        mPaint.setColor(0x800000FF);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        int count = getLineCount();
        Rect r = mRect;
        Paint paint = mPaint;

        for (int i = 0; i < count; i++) {
            int baseline = getLineBounds(i, r);

            canvas.drawLine(r.left, baseline + 1, r.right, baseline + 1, paint);
        }

        super.onDraw(canvas);
    }
} 

Now use object of LinedEditText class where you need.

An Example:

public class HorizontalLine extends Activity{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {   
        super.onCreate(savedInstanceState);
        setTitle("Android: Ruled/horizonal lines in Textview");

        LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        LayoutParams textViewLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

        LinedEditText et = new LinedEditText(this, null);
        et.setText("The name of our country is Bangladesh. I am proud of my country :)");
        et.setLayoutParams(textViewLayoutParams);

        ll.addView(et);
        this.setContentView(ll);

    }

}

The Output:

enter image description here

查看更多
登录 后发表回答