Wednesday 17 August 2016

GridView


GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid. The grid items are automatically inserted to the layout using a ListAdapter.


















































































Open the res/layout/main.xml file and insert the following:
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gridview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:columnWidth="90dp"
    android:numColumns="auto_fit"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:stretchMode="columnWidth"
    android:gravity="center"
/>
This GridView will fill the entire screen. The attributes are rather self explanatory. For more information about valid attributes, see the GridView reference.

Place GridView inside another layout
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="fill_parent"

    android:layout_height="wrap_content"

>

    <GridView android:layout_height="fill_parent"

        android:layout_width="fill_parent" android:id="@+id/gridview"

        android:numColumns="3"

        android:layout_alignParentTop="true" android:layout_alignParentLeft="true"/>

</RelativeLayout>

METHOD
Attributes of GridView:
Lets see different attributes of GridView which will be used while designing a custom grid view:
1.id: id is used to uniquely identify a GridView.
Below is the id attribute’s example code with explanation included in which we don’t specify the number of columns in a row that’s why the GridView behaves like a ListView.
Below is the id attribute example code for Gridview:
<GridView
android:id="@+id/simpleGridView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
2.numColumns: numColumn define how many columns to show. It  may be a integer value, such as “5” or auto_fit.
auto_fit  is used to display as many columns as possible to fill the available space on the screen.
Important Note: If we don’t specify numColumn property in GridView it behaves like a ListView with singleChoice.
Below is the numColumns example code where we define 4 columns to show in the screen.
<!-- numColumns example code -->
<GridView
android:id="@+id/simpleGridView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:numColumns="4"/> <!-- numColumns set to 4-->

numColumns attribute property in gridview android
3. horizontalSpacing: horizontalSpacing property is used to define the default horizontal spacing between columns. This could be in pixel(px),density pixel(dp) or scale independent pixel(sp).
Below is the horizontalSpacing example code with explanation included where horizontal spacing between grid items is 50 dp.
<!--Horizontal space example code in grid view-->>
<GridView
android:id="@+id/simpleGridView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:numColumns="3"
android:horizontalSpacing="50dp"/><!--50dp horizontal space between grid items-->
horizontal Spacing in Gridview
4.verticalSpacing: verticalSpacing property used to define the default vertical spacing between rows. This should be in px, dp or sp.
Below is the verticalSpacing example code with explanation included, where vertical spacing between grid items is 50dp.
<!-- Vertical space between grid items code -->
<GridView
android:id="@+id/simpleGridView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:numColumns="3"
android:verticalSpacing="50dp"/><!--50dp vertical space set between grid items-->
vertical Spacing in Grid View items android
5.columnWidth: columnWidth property specifies the fixed width of each column. This could be in px, dp or sp.
Below is the columnWidth example code. Here column width is 80dp and selected item’s background color is green which shows the actual width of a grid item.
Important Note: In the below code we also used listSelector property which define color for selected item. Also to see the output of columnWidth using listSelector we need to use Adapter which is our next topic. The below code is not sufficient to show you the output.
<!--columnWidth in Grid view code-->
<GridView
android:id="@+id/simpleGridView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:numColumns="3"
android:columnWidth="80dp"
android:listSelector="#0f0"/><!--define green color for selected item-->

column Width in Grid View android


android:stretchMode

Defines how columns should stretch to fill the available empty space, if any.
Must be one of the following constant values.
Constant
Value
Description
none
0
Stretching is disabled.
spacingWidth
1
The spacing between each column is stretched.
columnWidth
2
Each column is stretched equally.
spacingWidthUniform
3
The spacing between each column is uniformly stretched..


Adapters:
An adapter is a bridge between UI component and data source that helps us to fill data in UI component. It holds the data and sends the data to adapter view, then view can takes the data from the adapter view and shows the data on different views like as list view, grid view, spinner etc.
GridView and ListView both are subclasses of AdapterView and it can be populated by binding  to an Adapter, which retrieves the data from an external source and creates a View that represents each data entry. In android commonly used adapters are:
1. Array Adapter
2. Base Adapter
Now we explain these adapters in detail::
1. Array Adapter:
Whenever you have a list of single items which is backed by an array, you can use ArrayAdapter. For instance, list of phone contacts, countries or names.
By default, ArrayAdapter expects a Layout with a single TextView, If you want to use more complex views means more customization in grid items, please avoid ArrayAdapter and use custom adapters.
ArrayAdapter adapter = new ArrayAdapter<String>(this,R.layout.ListView,R.id.textView,StringArray);
2. Base Adapter:
Base Adapter is a common base class of a general implementation of an Adapter that can be used in GridView. Whenever you need a customized grid view you create your own adapter and extend base adapter in that. Base Adapter can be extended to create a custom Adapter for displaying custom grid items. ArrayAdapter is also an implementation of BaseAdapter.
















Program - 1
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="fill_parent"

    android:layout_height="wrap_content"

>

    <GridView android:layout_height="fill_parent"

        android:layout_width="fill_parent" android:id="@+id/gridview"

        android:numColumns="3"

        android:layout_alignParentTop="true" android:layout_alignParentLeft="true"/>

</RelativeLayout>

MainActivity.java
public class MainActivity extends Activity {





    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);



        GridView gridview = (GridView) findViewById(R.id.gridview);

        gridview.setAdapter(new ImageAdapter(this));



        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            public void onItemClick(AdapterView<?> parent, View v,

                                    int position, long id) {

                Toast.makeText(MainActivity.this, "" + position,

                        Toast.LENGTH_SHORT).show();

            }

        });



    }

    public class ImageAdapter extends BaseAdapter {

        private Context mContext;



        public ImageAdapter(Context c) {

            mContext = c;

        }



        public int getCount() {

            return mThumbIds.length;

        }



        public Object getItem(int position) {

            return null;

        }



        public long getItemId(int position) {

            return 0;

        }



        // create a new ImageView for each item referenced by the Adapter

        public View getView(int position, View convertView, ViewGroup parent) {

            ImageView imageView;

            if (convertView == null) {

                // if it's not recycled, initialize some attributes

                imageView = new ImageView(mContext);

                imageView.setLayoutParams(new GridView.LayoutParams(85, 85));

                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

                imageView.setPadding(8, 8, 8, 8);

            } else {

                imageView = (ImageView) convertView;

            }



            imageView.setImageResource(mThumbIds[position]);

            return imageView;

        }



        // references to our images

        private Integer[] mThumbIds = {

                R.drawable.sample_2, R.drawable.sample_3,

                R.drawable.sample_4, R.drawable.sample_5,

                R.drawable.sample_6, R.drawable.sample_7,

                R.drawable.sample_0, R.drawable.sample_1,

                R.drawable.sample_2, R.drawable.sample_3,

                R.drawable.sample_4, R.drawable.sample_5,

                R.drawable.sample_6, R.drawable.sample_7,

                R.drawable.sample_0, R.drawable.sample_1,

                R.drawable.sample_2, R.drawable.sample_3,

                R.drawable.sample_4, R.drawable.sample_5,

                R.drawable.sample_6, R.drawable.sample_7

        };

    }

}

























GridView + Base Adapter







22

No comments:

Post a Comment