How to use ruled/horizontal lines to align text in EditText in Android?

孤者浪人 提交于 2019-12-01 08:57:37

问题


Basically I want to do something like this in Android:

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:


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:



来源:https://stackoverflow.com/questions/8667506/how-to-use-ruled-horizontal-lines-to-align-text-in-edittext-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!