Android:在textview上绘制线条

Moy*_*een 6 android textview drawable

我在Android上问了一个前面标题为"Android:在TextView中采用Ruled/Horizo​​nal线"的问题:Textview中的Ruled/Horizo​​nal线.但我没有得到必要的答案.所以我想通过java在TextView上绘制线来实现这一点.有没有办法在TextView中绘制Line?或者如果我从java代码中获得结束,那么我将能够为每一行添加textview.任何帮助将受到高度赞赏.

Imr*_*ana 21

我正在使用在EditText中每行文本之间绘制线条的技术,然后我将通过将setKeyListener(null)设置为自定义EditText对象使EditText不可编辑,这样,EditText就像一个TextView :)


一个自定义的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);
    }
} 
Run Code Online (Sandbox Code Playgroud)

现在使用LinedEditText类的对象,您需要TextView并使其不可编辑.

一个例子:

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);
        et.setKeyListener(null);

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

    }

}
Run Code Online (Sandbox Code Playgroud)

et.setKeyListener(null)使EditText不可编辑,因此它就像一个TextView.


输出:

在此输入图像描述

游标问题:

如果你只使用et.setKeyListener(null)那么它只是没有监听密钥,但是用户可以在EditText上看到一个光标.如果您不想要此光标,只需通过添加以下行禁用EditText:

 et.setEnabled(false);
Run Code Online (Sandbox Code Playgroud)