Search code examples
androidbuttonbordertextview

Android Button or TextView Border programmatically without using setBackgroundDrawable method


I am looking for a way to put a border for either textview or a button programmatically without using the setBackgroundResource method.

The goal I am trying to achieve here is, to change the background color dynamically but with a fixed border. When I use the setBackgroundResource method for the background border, the border doesn't remain after changing the background color programmatically.


Solution

  • Simple example how could be this achieved:

    activity_main.xml

    <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" >
    
        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="5dp"
            android:text="@string/hello_world" />
    
    </RelativeLayout>
    

    MainActivity.java

    package com.exmple.test;
    
    import android.app.Activity;
    import android.graphics.drawable.GradientDrawable;
    import android.os.Bundle;
    import android.widget.TextView;
    
    public class MainActivity extends Activity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            GradientDrawable gd = new GradientDrawable();
            gd.setColor(0xFF00FF00); // Changes this drawbale to use a single color instead of a gradient
            gd.setCornerRadius(5);
            gd.setStroke(1, 0xFF000000);
            TextView tv = (TextView)findViewById(R.id.textView1);
            tv.setBackground(gd);
    
    
        }
    
    }