Thursday, 8 October 2015

GridView in Android

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


 activity_main.xml
-------------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   
xmlns:tools="http://schemas.android.com/tools"
   
xmlns:app="http://schemas.android.com/apk/res-auto"
   
android:layout_width="match_parent"
   
android:layout_height="match_parent"
   
app:layout_behavior="@string/appbar_scrolling_view_behavior"
   
tools:showIn="@layout/activity_main" tools:context=".MainActivity">

    <
GridView
       
android:layout_width="wrap_content"
        
android:layout_height="match_parent"
       
android:numColumns="3"
       
android:id="@+id/gridView" />
</
LinearLayout>
MainActivity.Java
---------------------------
package com.android.anil.gridview;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {
    GridView
gridView;
   
int[] images={R.mipmap.ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher,
            R.mipmap.
ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher,
            R.mipmap.
ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher,
            R.mipmap.
ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher,
            R.mipmap.
ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher,
            R.mipmap.
ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher,
            R.mipmap.
ic_launcher,R.mipmap.ic_launcher};
   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView(R.layout.
activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.
toolbar);
        setSupportActionBar(toolbar);
       
gridView=(GridView)findViewById(R.id.gridView);
        Myadapter myadapter=
new Myadapter();
       
gridView.setAdapter(myadapter);
    }
   
class Myadapter extends BaseAdapter{
       
@Override
       
public int getCount() {
           
return images.length;
        }

       
@Override
       
public Object getItem(int position) {
           
return null;
        }

       
@Override
       
public long getItemId(int position) {
           
return 0;
        }

       
@Override
       
public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView=
new ImageView(getApplicationContext());
            imageView.setImageResource(
images[position]);
           
return imageView;
        }
    }

}

Output is:
------------------------------


No comments:

Post a Comment