How do I add programmatically a border to a LinearLayout? Lets say we create this layout:
LinearLayout TitleLayout = new LinearLayout(getApplicationContext());
TitleLayout.setOrientation(LinearLayout.HORIZONTAL);
Then what do I do?
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.
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.
To create a linear layout in which each child uses the same amount of space on the screen, set the android:layout_height of each view to "0dp" (for a vertical layout) or the android:layout_width of each view to "0dp" (for a horizontal layout). Then set the android:layout_weight of each view to "1" .
I believe the answer above isn't correct: The question asks specifically for a programmatic version to do it and the first thing you see is xml. Secondly, doing partly xml is in my case almost never an option, so here's the correct answer:
//use a GradientDrawable with only one color set, to make it a solid color
GradientDrawable border = new GradientDrawable();
border.setColor(0xFFFFFFFF); //white background
border.setStroke(1, 0xFF000000); //black border with full opacity
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
TitleLayout.setBackgroundDrawable(border);
} else {
TitleLayout.setBackground(border);
}
Creat XML called border.xml in drawable folder as below :
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="#FF0000" />
</shape>
</item>
<item android:left="5dp" android:right="5dp" android:top="5dp" >
<shape android:shape="rectangle">
<solid android:color="#000000" />
</shape>
</item>
</layer-list>
then add this to linear layout as backgound as this:
android:background="@drawable/border"
Programmatically
TitleLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.border))
EDIT :
Since Jelly Bean, this method (setBackgroundDrawable has been deprecated), so yet you have to use this one :
TitleLayout.setBackground(getResources().getDrawable(R.drawable.border));
hope this help .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With