TextView Border
To draw a border around TextView, you can use background attribute of the TextView widget and assign a shape to it. The shape is such that the stroke on the shape outline appears as border.
The sample code to draw border for TextView is
<TextView
android:text="Hello World!"
android:background="@drawable/border"/>
You have to create the following drawable file in res/drawable/ folder.
border.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<solid android:color="@android:color/white" />
<stroke android:width="2dp" android:color="#4CAF50"/>
</shape>
Example
Create an Android Application with Kotlin support and Empty Activity.
Right click on res/drawable folder and click on New -> Drawable Resource File. Give file name as border(or any other name) and Root element as shape. border.xml file will be created in res/drawable/ folder. Copy the following code into the border.xml file.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<solid android:color="@android:color/white" />
<stroke android:width="2dp" android:color="#4CAF50"/>
</shape>
You may change the border width and color.
Create a TextView widget in activity_main.xml with background attribute set to border.xml as shown below.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="30sp"
android:textAlignment="center"
android:layout_margin="10dp"
android:background="@drawable/border"
android:text="Hello World" />
</LinearLayout>
MainActivity.kt
package com.kotlinandroid.myapp
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
Screenshot