Display border around TextView on button click programming coding.
Dynamically adding border around textview with the use of another layout xml file and set that layout file using setBackgroundResource() function on button click event. So here is the complete step by step tutorial for Add border to textview android programmatically.
How to Add border to textview android programmatically.
Code for MainActivity.java file.
package com.textviewborder_android_examples.com;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView txt1;
Button bt1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt1 = (TextView)findViewById(R.id.textView1);
bt1 = (Button)findViewById(R.id.button1);
bt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Apply textview_border.xml file here dynamically in button click.
txt1.setBackgroundResource(R.layout.textview_border);
}
});
}
}
Code for activity_main.xml layout file.
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.textviewborder_android_examples.com.MainActivity" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="183dp" android:text="Android-Examples.com is one of the best website to learn android app development tutorials." android:textAppearance="?android:attr/textAppearanceMedium" android:padding="10dp" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textView1" android:layout_centerHorizontal="true" android:layout_marginTop="21dp" android:text="Click Here to Put border around TextView" /> </RelativeLayout>
Code for textview_border.xml file.
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" > <solid android:color="#fafbfb" /> <stroke android:width="3dp" android:color="#fd0261" ></stroke> </shape>
Screenshots: