Android linearlayout border

By default the LinearLayout does not have a border. In case that you need to apply the border to the LinearLayout, this Android tip is useful to you. I will help you walk through the process of adding border to the layout.
First of all, you have to define an xml file in the res/drawable directory that will be used as the background of the layout. In my case, I create a file called border.xml. In the file, you define a shape (e.g. rectangle, oval). Then you specify attributes of the shape. The width and color of the border are specified in the tag. If you want to apply corners and paddings to the shape, you use and tags.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android= "http://schemas.android.com/apk/res/android"
   android:shape="rectangle">
   <!--stroke width and color-->
   <stroke
     android:width="8dp"
     android:color="#3F51B5"/>
   <!-- corner radius-->
   <corners
     android:radius="10dp"/>
   <!--paddings-->
   <padding
     android:left="15dp"
     android:top="10dp"
     android:right="15dp"
     android:bottom="10dp"/>
</shape>

After you defined the border in xml file, you can apply the border to the layout ether by xml or java code. To apply the border to the layout by xml, you open the activity_main.xml file and add the background attribute the LinearLayout. The value of the attribute will be @drawable/border.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:id="@+id/llayout"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   tools:context=".MainActivity"  
   android:background="@drawable/border"
  >

   <Button
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="Button1"
     />
   <Button
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="Button2"
     />

</LinearLayout>



Alternatively, you can apply the border to the Linearlayout by writing the following code in the onCreate() method of the MainActivity class.

LinearLayout linearLayout=(LinearLayout)findViewById(R.id.llayout);
linearLayout.setBackgroundResource(R.drawable.border);


linearlayout border

Posted by: Dara | post date: 05-01-2015 | Subject: Android Apps Development

write programming tip




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.