【问题标题】:How to use ruled/horizontal lines to align text in EditText in Android?如何在 Android 的 EditText 中使用规则/水平线对齐文本?
【发布时间】:2012-05-27 07:44:38
【问题描述】:

基本上我想在 Android 中做这样的事情:

我正在尝试在自定义 EditText 中绘制水平线,然后在这些线上输入。

我使用文本大小来表示两条水平线之间的距离。但是,光标大小和文本大小不一样。因此,我无法保持将文本“放在”这些行上。

文本基础与这些水平线的对齐方式不正确。

这是用于绘制线条的代码:-

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

EditText 不提供任何获取光标大小的方法。

如果有任何解决方法或任何其他更好的方法,请提出建议。

【问题讨论】:

    标签: java android android-edittext textview android-custom-view


    【解决方案1】:

    一个自定义的EditText,在显示的每行文本之间画线:

    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);
        }
    } 
    

    现在在你需要的地方使用 LinedEditText 类的对象。

    一个例子:

    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);
    
        }
    
    }
    

    输出:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-11
      • 2013-03-12
      • 1970-01-01
      • 1970-01-01
      • 2017-08-30
      • 2019-02-04
      • 2023-03-18
      相关资源
      最近更新 更多