Android:Textview中的直线/水平线

Moy*_*een 2 android textview

在Android中,我有一个TextView,它的内容将是动态的.我想在每行文字后面显示一条水平线.我搜索了很多并找到了EditText(如何使用统治/水平线来对齐Android中的EditText文本?).我正在计划绘制动态TextView和它们下面的水平线.但我不知道怎样才能检测出行尾.任何帮助将受到高度赞赏.我希望与如何使用统治/水平线在Android中的EditText中对齐文本的附加图像具有相同的效果

Imr*_*ana 6

我正在使用在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)