Using following code , we can create any view with custom background and border color for all the Widgets in Android application.
activity_main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity"
android:background="@android:color/white"
>
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sample TextView..."
android:padding="15dp"
android:textSize="25dp"
android:textColor="#ff4146ff"
/>
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Apply Rounded Border"
android:layout_below="@id/tv"
/>
</RelativeLayout>
MainActivity.java
package com.cfsuman.me.androidcodesnippets;
import android.graphics.Color;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.graphics.drawable.GradientDrawable;
public class MainActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get the widgets reference from XML layout
RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
final TextView tv = (TextView) findViewById(R.id.tv);
Button btn = (Button) findViewById(R.id.btn);
// Set a click listener for Button widget
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Initialize a new GradientDrawable
GradientDrawable gd = new GradientDrawable();
// Specify the shape of drawable
gd.setShape(GradientDrawable.RECTANGLE);
// Set the fill color of drawable
gd.setColor(Color.TRANSPARENT); // make the background transparent
// Create a 2 pixels width red colored border for drawable
gd.setStroke(2, Color.RED); // border width and color
// Make the border rounded
gd.setCornerRadius(15.0f); // border corner radius
// Finally, apply the GradientDrawable as TextView background
tv.setBackground(gd);
}
});
}
}
