How to give and show border to whole gridview layout background programmatically using xml layout file.
In this tutorial we are designing a simple gridview layout with border. To add border we have using external custom layout xml file and setting up that file as grid view background. So here is the complete step by step tutorial for How to Set/Add border around gridview in android.
How to Set/Add border around gridview in android.
Code for MainActivity.java file.
package com.gridviewwithborder_android_examples.com; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import android.app.Activity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.GridView; public class MainActivity extends Activity { GridView gridview; String[] item = new String[]{ "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX" }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); gridview = (GridView)findViewById(R.id.gridView1); List<String> ITEM_LIST = new ArrayList<String>(Arrays.asList(item)); gridview.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1,ITEM_LIST)); } }
Code for activity_main.xml layout file.
<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" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.gridviewwithborder_android_examples.com.MainActivity" > <GridView android:id="@+id/gridView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:numColumns="3" android:background="@layout/gridview_border" > </GridView> </RelativeLayout>
Code for gridview_border.xml file.
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item> <shape android:shape="rectangle"> <solid android:color="#00fb9a"/> <stroke android:color="#5d05ff" android:width="3dp" /> </shape> </item> </selector>
Screenshot: