Android:水平线,中间有文字

Asf*_*sfi 12 android

我想知道如何用中间的文本做这个水平线,看看这个截图:

在此输入图像描述

有人有想法在Android上这样做吗?我找到了如何做一个水平线,但从来没有用文字.

谢谢 !

Boj*_*man 49

只需更改颜色以匹配图像上的颜色即可.我还建议你使用渐变作为那些虚拟视图的背景,如果你花一点时间,它看起来比屏幕截图好很多.

 <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true">

        <TextView
            android:id="@+id/tvText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:text="lala"
            android:textColor="#FFFFFF"/>

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_centerVertical="true"
            android:layout_marginLeft="16dp"
            android:layout_toLeftOf="@id/tvText"
            android:background="#FF0000"
            />

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_centerVertical="true"
            android:layout_marginRight="16dp"
            android:layout_toRightOf="@id/tvText"
            android:background="#FF0000"
            />

    </RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


小智 5

public class CenterLineTextView extends android.support.v7.widget.AppCompatTextView {

private final Rect mBounds = new Rect();
private final Paint mPaint = new Paint();
private int mPadding;
private int mStroke;

public CenterLineTextView(Context context) {
    super(context);
    init();
}

public CenterLineTextView(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    init();
}

public CenterLineTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init();
}

private void init() {
    if (isInEditMode()) {
        return;
    }
    setGravity(Gravity.CENTER);
    mStroke = getContext().getResources().getDimensionPixelSize(R.dimen.divider);
    mPadding = getContext().getResources().getDimensionPixelSize(R.dimen.login_or_padding);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    mPaint.setStrokeWidth(mStroke);
    mPaint.setColor(getPaint().getColor());
    getPaint().getTextBounds(getText().toString(), 0, getText().length(), mBounds);
    canvas.drawLine(0, getHeight() / 2, (getWidth() - mBounds.right) / 2 - mPadding, getHeight() / 2, mPaint);
    canvas.drawLine(mPadding + (getWidth() + mBounds.right) / 2, getHeight() / 2, getWidth(), getHeight() / 2, mPaint);
}
}
Run Code Online (Sandbox Code Playgroud)