Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Way to appear bordered text on the TextView?

Is there a way to appear bordered text on the TextView ?

like image 353
AndroiDBeginner Avatar asked Jan 08 '10 10:01

AndroiDBeginner


People also ask

How do you add a border in TextView?

To add a border to Android TextView we need to create an XML containing shape as a rectangle file under the drawable's folder and set it as background to the TextView. <stroke> tag is used to set the border width and color.

How do you add a border to text on android?

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. In the above code we have taken one text view with background as border so we need to create a file in drawable as boarder.

Which attribute is used to show any text inside TextView?

We use attribute android: hint= "Text will show here", so if we will set the TextView in the MainActivity.


2 Answers

I would suggest to extend TextView
See 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);       
    }
}

Than use it in layout 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>
like image 53
Maksym Gontar Avatar answered Nov 15 '22 06:11

Maksym Gontar


Most simple way is use a 9 patch background.

<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" />
like image 24
Cytown Avatar answered Nov 15 '22 04:11

Cytown