Programmatically add a border to LinearLayout

How to add a border programmatically to LinearLayout? Let's say we create this layout:

LinearLayout TitleLayout = new LinearLayout(getApplicationContext()); TitleLayout.setOrientation(LinearLayout.HORIZONTAL); 

Then what should I do?

+6
source share
2 answers

I believe the answer above is incorrect: the question is specifically for the software version, and the first thing you see is xml . Secondly, partially xml execution is almost never an option in my case, so the correct answer is:

  //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); } 
+32
source

Create an XML called border.xml in the folder with the extension as shown 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 the linear layout as a backgound like this:

 android:background="@drawable/border" 

Program

 TitleLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.border)) 

EDIT:

Since Jelly Bean, this method (setBackgroundDrawable is deprecated), so you should use it:

 TitleLayout.setBackground(getResources().getDrawable(R.drawable.border)); 

hope this help.

+4
source

Source: https://habr.com/ru/post/946349/


All Articles