Android - 在TextView上显示带边框文本的方法?

时间:2010-01-08 10:24:10

标签: android user-interface custom-controls border

有没有办法在TextView上显示带边框的文字?

2 个答案:

答案 0 :(得分:16)

我建议延长TextView
Android Custom Component Guide

android_text_border

package samples.test;
public class MyTextView extends TextView {
    public MyTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyTextView(Context context) {
        super(context);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Rect rect = new Rect();
        Paint paint = new Paint();
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(Color.WHITE);
        paint.setStrokeWidth(3);
        getLocalVisibleRect(rect);
        canvas.drawRect(rect, paint);       
    }
}

比在布局xml:

中使用它
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <samples.test.MyTextView android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="@string/hello" />
</LinearLayout>

答案 1 :(得分:5)

最简单的方法是使用9补丁背景。

<TextView android:id="@+id/txt_target"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="000000000"
            android:gravity="center_vertical"
            android:background="@drawable/textfield_default"
            android:layout_marginRight="5dip" />