Search Wikipedia

Search results

Dec 3, 2013

Basic GridView Layout in Android

Creating a Basic GridView Layout 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.

Today i am gonna create a simple Gridview layout.Now  I prepare images which i want to show in grid layout and place them in res->drawable-hdpi folder.

Images in Drawable-hdpi which will be shown in Gridview

I go to activity_main.xml and drag gridview layout from Palette or I can also write code directly for gridview which will be like this:

activity_main.xml


Now  I create a new class by right clicking Src->Package folder->New->Class 
and called it "Gridadap.java" and write these codes.



import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class Gridadap extends BaseAdapter{
public Integer[] ImageIds = { R.drawable.a, R.drawable.e,R.drawable.f
,R.drawable.r, R.drawable.v
 // these are the images to be shown in gridview
};
private Context mContext;
public Gridadap(Context c){
mContext=c;
}

@Override
public int getCount() {
return ImageIds.length;
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return ImageIds[position];
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}

@Override
public View getView(int position, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
ImageView iv = new ImageView(mContext);
iv.setImageResource(ImageIds[position]);
iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
iv.setLayoutParams(new GridView.LayoutParams(70, 70));
return iv;
}

Gridadap.java


After that i write these codes in MainActivity.java and write these codes:


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gv1 = (GridView) findViewById(R.id.gridView1);
 gv1.setAdapter(new Gridadap(this));


MainActivity.java

Now my project is ready to run and it looks like this.


Running my project

No comments:

Post a Comment

Did this post help you? Do you have any questions? Drop your thoughts here...

}