Wednesday, July 24, 2013

Android Custom Grid View Example | Image and Text in GridView in Android | Gridview demo in Android

Hello Friends,
Today I am sharing very simple useful post "Custom Grid View in Android".
All the code are given below just copy paste and enjoy. You can download zip folder from github also...

EDIT:On Item Click Make Toast



MainActivity.java


package com.manish.customgridview;

import java.util.ArrayList;


import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.Toast;
/**
 * 
 * @author manish.s
 *
 */

public class MainActivity extends Activity {
 GridView gridView;
 ArrayList<Item> gridArray = new ArrayList<Item>();
  CustomGridViewAdapter customGridAdapter;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  //set grid view item
  Bitmap homeIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.home);
  Bitmap userIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.personal);
  
  gridArray.add(new Item(homeIcon,"Home"));
  gridArray.add(new Item(userIcon,"User"));
  gridArray.add(new Item(homeIcon,"House"));
  gridArray.add(new Item(userIcon,"Friend"));
  gridArray.add(new Item(homeIcon,"Home"));
  gridArray.add(new Item(userIcon,"Personal"));
  gridArray.add(new Item(homeIcon,"Home"));
  gridArray.add(new Item(userIcon,"User"));
  gridArray.add(new Item(homeIcon,"Building"));
  gridArray.add(new Item(userIcon,"User"));
  gridArray.add(new Item(homeIcon,"Home"));
  gridArray.add(new Item(userIcon,"xyz"));
  
  
  gridView = (GridView) findViewById(R.id.gridView1);
  customGridAdapter = new CustomGridViewAdapter(this, R.layout.row_grid, gridArray);
  gridView.setAdapter(customGridAdapter);
  
  gridView.setOnItemClickListener(new OnItemClickListener() {

   @Override
   public void onItemClick(AdapterView<?> arg0, View v, int position,
     long arg3) {
    Toast.makeText(getApplicationContext(),gridArray.get(position).getTitle(), Toast.LENGTH_SHORT).show();
    
   }
  });
 }

}

CustomGridViewAdapter.java


package com.manish.customgridview;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * 
 * @author manish.s
 *
 */
public class CustomGridViewAdapter extends ArrayAdapter<Item> {
 Context context;
 int layoutResourceId;
 ArrayList<Item> data = new ArrayList<Item>();

 public CustomGridViewAdapter(Context context, int layoutResourceId,
   ArrayList<Item> data) {
  super(context, layoutResourceId, data);
  this.layoutResourceId = layoutResourceId;
  this.context = context;
  this.data = data;
 }

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
  View row = convertView;
  RecordHolder holder = null;

  if (row == null) {
   LayoutInflater inflater = ((Activity) context).getLayoutInflater();
   row = inflater.inflate(layoutResourceId, parent, false);

   holder = new RecordHolder();
   holder.txtTitle = (TextView) row.findViewById(R.id.item_text);
   holder.imageItem = (ImageView) row.findViewById(R.id.item_image);
   row.setTag(holder);
  } else {
   holder = (RecordHolder) row.getTag();
  }

  Item item = data.get(position);
  holder.txtTitle.setText(item.getTitle());
  holder.imageItem.setImageBitmap(item.getImage());
  return row;

 }

 static class RecordHolder {
  TextView txtTitle;
  ImageView imageItem;

 }
}

activity_main.xml


<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=".MainActivity" >

     <GridView
        android:id="@+id/gridView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="4dp"
        android:columnWidth="80dp"
        android:gravity="center"
        android:numColumns="auto_fit"
        android:stretchMode="columnWidth" >
    </GridView>

</RelativeLayout>

row_grid.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="5dp" >

    <ImageView
        android:id="@+id/item_image"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginRight="10dp"
        android:src="@drawable/home" >
    </ImageView>

    <TextView
        android:id="@+id/item_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:textSize="15sp" >
    </TextView>

</LinearLayout>

AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.manish.customgridview"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.manish.customgridview.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>



Download Zip Code


Thanks!

142 comments:

  1. Manish thank u for responding. I use that code thank u . and please post web services and xml parsing program please

    ReplyDelete
    Replies
    1. thank u for Android Custom Grid View Example.i am trying create data grid view but,how to create data grid view for android app,jut like .net,we can edit,delete,insert data in data grid view.please help me...

      Delete
  2. Replies
    1. Hi manish thanku for giving rly to all. Please give how to access data from server (like flipkart, googleplay) please give some hint or post one example.

      Delete
    2. Hi Rajashekar!
      Which example you looking for? integrate service or something else?

      Delete
    3. Hi Rajashekar!
      Which example you looking for? integrate service or something else?

      Delete
  3. Thank u so much for this post...

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. Since looking at android development, particularly custom Views and Adapters, I found this example complete in terms of the custom adapters and inflation of view. I did not run but hey. I can't download everything. ;-)

    Couple of questions.

    1. Why define RecorderHolder class as static?
    2. How would you modify this example to use a custom view that extends the View class?

    ReplyDelete
    Replies
    1. Please try again may be some problem at your end because other's visitor using same git repository.

      1)RecordHolder class is static because we can call it any where as you know static definitions. But it is not must using like that only, you can use is directly without any static class.

      See this code-

      public class ContactImageAdapter extends ArrayAdapter {
      Context context;
      int layoutResourceId;
      LinearLayout linearMain;
      ArrayList data = new ArrayList();

      public ContactImageAdapter(Context context, int layoutResourceId,
      ArrayList data) {
      super(context, layoutResourceId, data);
      this.layoutResourceId = layoutResourceId;
      this.context = context;
      this.data = data;
      }

      @Override
      public View getView(int position, View convertView, ViewGroup parent) {
      View row = convertView;

      if (row == null) {
      LayoutInflater inflater = ((Activity) context).getLayoutInflater();
      row = inflater.inflate(layoutResourceId, parent, false);

      linearMain = (LinearLayout) row.findViewById(R.id.lineraMain);

      Contact myImage = data.get(position);
      for (int j = 0; j < myImage.getName().length; j++) {
      TextView label = new TextView(context);
      label.setText(myImage.name[j]);
      linearMain.addView(label);
      }
      ImageView image = new ImageView(context);
      int outImage = myImage.image;
      image.setImageResource(outImage);
      linearMain.addView(image);
      }

      return row;

      }

      }

      2) This demo is already custom grid-view. what you want do more? Please do Google for your specific requirement.

      Delete
  6. sir,
    i am working on city guide project its my first project on android.
    can you help me??

    ReplyDelete
    Replies
    1. Yes sure, If you have any doubt in code, you can ask. But not whole project, just i can help you in logic.
      Thanks!

      Delete
  7. thanks manish I use that code for my app.
    you are a very good developer and helpful person.

    ReplyDelete
  8. Hi!
    Manish , I want to add vertically lines dynamically in my GridView....Can you help me about this.....
    I would be very thankful to you in this regards!!!

    Thanks

    ReplyDelete
  9. Hi!
    Manish I want to add vertical lines dynamically in gridView ..... kindly help me

    Thanks

    ReplyDelete
  10. Hi!
    Manish , I want to add vertical lines dynamically in gridView.....kindly help me

    Thanks,

    ReplyDelete
    Replies
    1. What you mean by vertical line? will you explain in detail please? You want 1x3 girdview instead of 3x3? or you want item inside box like windows app?

      Delete
    2. Suppose, if user select number 3 then these type of 3 lines should be displayed in my mobile screen
      ----- ----- -----
      These lines should be displayed above my gridView.....my gridView have alphabets

      Delete
    3. Hi saud, I am sorry for late response. Still i did not understood your requirement. well i think you want display selected row item above the gridview right?
      so just get postion of that image like you clicked number 4 that means its belongs from row 2. now you want display item number 4,5,6 on the top of gridview right?
      Okay so just create a LinearLayout above to your gridview and inside that 3 imagevIew and set visibility to invisible. and on click item set that row item into imageview and swt visibility true.

      Hope it will help you!

      Delete
  11. When I click on any of the item it does nothing . I tested using Toast but no way. So how to fix this.

    ReplyDelete
  12. Hi Manish, thanks for good post...
    I have an app that contain ListView, how to convert this listview to GridView ?
    The following is my code:

    public class CustomAdapter extends BaseAdapter{
    private Context context;
    private List myItem;

    public CustomAdapter(Context context, List deviceList ) {
    this.context = context;
    this.myItem = deviceList;
    }
    public int getCount() {
    return myItem.size();
    }
    public Object getItem(int position) {
    return myItem.get(position);
    }
    public long getItemId(int position) {
    return position;
    }
    public View getView(int position, View convertView, ViewGroup parent)
    {
    MyBean item = myItem.get(position);
    View view = new CustomAdapterView(this.context, item );
    return view;
    }
    }

    public class CustomAdapterView extends RelativeLayout {
    public CustomAdapterView(Context context, MyBean myItem) {
    super(context);
    LinearLayout layout = new LinearLayout(context);
    layout.setOrientation(LinearLayout.HORIZONTAL);
    setPadding(10, 10, 0, 10);

    RelativeLayout.LayoutParams Params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    Params.setMargins(6, 0, 6, 0);
    ImageView mLogo = new ImageView(context);
    if (myItem.getImageName()!=null) mLogo.setImageBitmap(MyImageClass.getImage(myItem.getImageName()));
    layout.addView(mLogo, Params);

    Params = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
    TextView textLabel = new TextView(context);
    textLabel.setTextSize(16);
    textLabel.setText(myItem.getLabel());
    layout.addView(textLabel);

    addView(layout, Params);
    }
    }

    ReplyDelete
    Replies
    1. How can you convert a listview into gridview? if you are talking about your custom adapter then yes its looking okay and you can use it with gridview. Just create gridview instead of listview in your activity class.

      Thanks.

      Delete
  13. Hi, Manish!!

    I'm starting with android and I think your blog is fantastic!

    I have a question, I tried to adapt the GridView to an application that I have sound buttons on a LinearLayout. but I would like to adapt it to the GridView

    I encounter a problem, I assigned a button and the called ID from mainactivity

    public void clickHandler(View v)
    {
    int id = v.getId();
    switch (id)
    {
    R.id.btn2 case:
    snd.play (sound1);
    Log.i ("---", "bt2");
    break;

    R.id.btn3 case:
    snd.play (sound2);
    Log.i ("---", "bt3");
    break;
    (...)
    but now I find that in the gridview I can not use this function because we donot like picking the id of each button.

    Can you help me please? thanks

    ReplyDelete
    Replies
    1. In that ArrayList pass sound too and use getter-setter to get song on ta that item.
      like-
      gridArray.add(new Item(homeIcon,"Home",R.anim.song1.mp3));
      gridArray.add(new Item(userIcon,"User",R.anim.song.mp3));

      And now on that item click just create object of audio player and play that song.

      Delete
  14. Is a very good thing. Thank you for the good things to share.

    ReplyDelete
  15. Hi Manish,
    Thanks a lot for this post!!!
    I need your help as I am facing one issue. In my gridview I am showing text field only not images,
    I have followed all the steps and its working fine but my requirement is that my gridview is having fix 6 columns and i wanted to apply color to textview in second column depending on its text. e.g if text is "New" i want to apply color blue ,if it is "Working" i want to apply color orange.etc

    I am also able to do this with following code in "CustomGridViewAdapter.java" before returning row

    if (holder.txtTitle.getText().toString().equals("New")) {
    holder.txtTitle.setTextColor(Color.parseColor("#1E29FF"));
    } else if (holder.txtTitle.getText().toString().equals("Working")) {
    item.title.toString().equals("Working")
    holder.txtTitle.setTextColor(Color.parseColor("#FFA500"));
    }

    This is also changing color as per my requirement but main problem is that if list is very large and If I scroll up or down it assigning color to other textview in other columns.

    Could you please give any suggestion,Plzzzz.......It's very urgent!!!!!

    Let me know if you need any clarification from my side...

    ReplyDelete
    Replies
    1. I can't say any thing with out code but please try else case also in your adapter-

      if (holder.txtTitle.getText().toString().equals("New")) {
      holder.txtTitle.setTextColor(Color.parseColor("#1E29FF"));
      } else if (holder.txtTitle.getText().toString().equals("Working")) {
      item.title.toString().equals("Working")
      holder.txtTitle.setTextColor(Color.parseColor("#FFA500"));
      }
      else {
      holder.txtTitle.setTextColor(Color.parseColor("Color.BLACK"));
      }

      Delete
  16. This comment has been removed by the author.

    ReplyDelete
  17. This comment has been removed by the author.

    ReplyDelete
  18. Manish,

    I have used code same as of your code, only image is not there in my app.

    I have implemented solution you suggested, it's working fine!!!!Thanks a lot!!!.but is it right way????

    ReplyDelete
  19. Thanks a lot Manish!!!!!!! It was very urgent!!!!!

    ReplyDelete
  20. Hi, Can you show me how to download images from web (using image urls) and then show them in a grid view efficiently?

    ReplyDelete
  21. Hi Manish,

    I want to apply style to gridview in this example as for a whole row apply diffrent color or drawable resource, on click of particular row want to change it's color. I tried in getview method to apply background color or resource but its changing it for each cell but i want to apply it for whole row.

    Also on click of any cell want to select whole row and it's data, could you please give your thought on this.....waiting for your reply!!!

    ReplyDelete
    Replies
    1. do some R&D dear. If you are able to get row then sure you can give effect to that row. please try at your end..

      Delete
  22. Hey Manish,

    I got the solution for this instead of grid view I used Custom list view, its doing same thing that i needed..Thanks!!!!

    ReplyDelete
  23. hi manish ,
    I used this code its working good and Iam new for android developing side ,If any doubts plz help me

    ReplyDelete
  24. hy manish..i am new in android develpment..i m making a app using grid view and i want to add a text or label on each icon i.e. gallery, calendar etc..
    i m trying bt i got the "unreachable code" error at ine num 53...
    i m sending my code to u..will u pls help me in that ASAP...




    package com.example.gridexample;

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

    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;
    }


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


    if (convertView==null) {

    imageView=new ImageView(mContext);
    imageView.setLayoutParams(new GridView.LayoutParams(150,150));
    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
    imageView.setPadding(8,8,8,8);

    }
    else {
    imageView = (ImageView) convertView;
    }

    imageView.setImageResource(mThumbIds[position]);
    return imageView;


    TextView tv = (TextView)convertView.findViewById(R.id.icon_text);
    tv.setText(names[position]);
    return convertView;
    }

    private Integer[] mThumbIds = {

    R.drawable.git,
    R.drawable.map,
    R.drawable.gallery,
    R.drawable.circular,
    R.drawable.academic,
    R.drawable.calendar,
    R.drawable.admission,
    R.drawable.directory,
    R.drawable.faq,
    };

    private String[] names={"1","2","3","4","5","6","7","8","9",};

    }

    ReplyDelete
    Replies
    1. Why you want doing like that? Above code already have Label like- Home etc..

      Delete
  25. Hi Manish.

    I want to Textbox(EditText) nearest to the all images. So how it is possible ? Please tell me something about your idea.
    If you have ready any code so please send me. Thanks Manish. Nice your Articles.

    ReplyDelete
    Replies
    1. Please make changes into your Adapter class and row.xml add an edittext below of your imageview.

      Delete
  26. Hi, i tried your code and i find it very usufull but i have a problem with my code because i call the activity containing the grid view from the main activity and it doesn't work. Then I tried without a main page, opening directly the gridview, and it worked properly. So, which could be the problem? thank you in advance

    ReplyDelete
    Replies
    1. I don't thing there should be any issue. From where you are calling that page not a matter it should work.. Have you declare that activity in manifest.xml?

      well what error you are getting? And how you are calling grid-view activity?

      Delete
    2. I'm calling the grid view activity through an intent in the main activity...
      The grid activity is declared in the manifest.xml
      I can't say you the error because eclipse open a 'source not found' page.
      I'm developing my first app, sorry:)

      Delete
    3. Can you please share the way you are opening grid view page using intent?
      and name of both 2 class, MainActivity and GridView.

      Delete
    4. sure:

      public void openSubjectsActivity(View view) {
      Intent intent = new Intent(this, Subjects.class);
      startActivity(intent);
      }

      the activity are MainActivity and Subjects

      Delete
    5. And from where you called this method "openSubjectsActivity"? onCreate method or click of any button? I think you miss to call this method right?

      Delete
    6. The strange thing is that if in Subjects method there is another kind of code that use as adapter an ImageAdapter that doesn't iclude the inflate the app run correctly

      Delete
    7. So just do one thing inside your image click direct paste these 2 line-

      img.setOnClickListner(new OnClickLictner){
      Intent intent = new Intent(MainActivity.this, Subjects.class);
      startActivity(intent);
      }

      Note: Please add sufficient code, above code is only an idea. and please let me know the result.

      Delete
    8. where i have to paste these lines?
      OnClickListener is not in my code...

      Delete
    9. you said that you open class activity "click on an ImageView" ? if no onClickListner then how you able to click an image?

      Delete
    10. in the xml layout of MainActivity i have

      Delete
    11. yes i know you have that image-view inside your layout but you have to press/click from your java class using onClickListner. I think this is the thing what you are missing if I am not wrong. Please take help from any demo application for go one page to another.

      Delete
  27. android:onClick="openSubjectsActivity"

    ReplyDelete
    Replies
    1. is this take to you on next page? have you any log on next page?

      Delete
    2. if everything okay so now please use debugger and see flow of app. what is the wrong with this.

      Delete
    3. the method bring me to the other activity correctly if the other activity does not use the adapter ...is this the problem that is very strange for me...

      Delete
    4. i'll try to debug...if i don't solve the problem can i post you my code?

      Delete
  28. i have read the demo application but they not use the OnClickListener...they open other activity only putting in the xml android:onClick="openSubjectsActivity" and then writing the method

    public void openSubjectsActivity(View view) {
    Intent intent = new Intent(this, Subjects.class);
    startActivity(intent);
    }

    ReplyDelete
    Replies
    1. Now it is stranger for to me :)
      well try it at your end if you don't got anything please email your demo application @manishupacc@gmail.com
      I will look on it tomorrow.

      And you are doing pretty good, your calling style is okay no issue here.

      Thanks!

      Delete
  29. i m getting problem in gridarray .add(new Item(home, "home"); please help me

    ReplyDelete
  30. hieeee.. manish. i m using following code for initializing gridlayout.

    Resources r = getResources();
    float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
    AppConstant.GRID_PADDING, r.getDisplayMetrics());

    columnWidth = (int) ((utils.getScreenWidth() - ((AppConstant.NUM_OF_COLUMNS + 1) * padding)) / AppConstant.NUM_OF_COLUMNS);
    System.out.println("grid......");
    gridView.setNumColumns(AppConstant.NUM_OF_COLUMNS);
    gridView.setColumnWidth(columnWidth);
    gridView.setStretchMode(GridView.NO_STRETCH);
    gridView.setPadding((int) padding, (int) padding, (int) padding,
    (int) padding);
    gridView.setHorizontalSpacing((int) padding);
    gridView.setVerticalSpacing((int) padding);

    but my imageview getting resize in every image..

    ReplyDelete
  31. Manish Srivastava, how could i implement a panel with more than one gridView, like in whatsApp emoticons panel which is divided by category ?

    ReplyDelete
  32. Hi Manish Srivastava'm working with gridviews with pictures, 2 Buttons 1 EditText, a button is to add one variable and the other is to subtract the same variable in a unit,

    In each box of gridview I have two buttons and one EditText but i can't make the buttons work separately.

    I have two methods one is to increment a variable either to decrease by one.

    When I press the button to add it done correctly but if I press the same button in another continuous box on the continuation of the short, follow your tutorial but when adding a button I can not see the title of the image to give click. as podira make the buttons work separately in each section of the gridview


    Greetings

    ReplyDelete
  33. hey Manish Srivastava,
    thanks for this android tutorial it really helps.
    but you know i want to show this grid vertically can you explain me how i can do that thing with your code. ?

    ReplyDelete
  34. Manish, Great post.
    i have a small problem i wish you can help me with.

    i have arranged some app icons and their label underneath the, and i show it in a frid view that was built according to your example.
    everything works good when i run it on an emulator but when running on a real device it doesnt show the textView labels. (only the apps icons are showed)
    any idea what is the reason for that?

    ReplyDelete
  35. Hi Manish,

    How can I refresh this gridview with new data on button click?Could you please give any idea?

    ReplyDelete
  36. Hi manish ,
    How can i form data in list view by using soap webservices in android....please give tutorial

    ReplyDelete
  37. Hello Manish, great tutorial but I am trying to implement your code for a Tabbed Fragment Layout but I am getting errors. I am new to Android and I was wondering if you could help me out.

    Let me know so that I can post my full code.

    ReplyDelete
    Replies
    1. Can you share your error log please? Well you need to inflate your view inside fragment..

      Delete
  38. How can I refresh this gridview with new data on button click?Could you please give any idea?

    ReplyDelete
    Replies
    1. Rebind the adapter or use notify data change.

      Delete
    2. plz explain me by an example....i am new in android

      Delete
  39. Hi, I've got a nullpointer error in my getview - setText . would you help to solve? I found most posts related on this but still cannot fix my problem.

    ReplyDelete
  40. Hi manish,

    Nice example


    but i want something else. i m using two buttons in my custom listview with custom adapter. The scenario is select all and deselect all and select individually clicking on that particular position. I have successfully done the select all and de select all. but problem i m facing is in by selecting one by one clicking on it.
    Like, If , i m clicking on zero Position's button the visibility of select button is set to invisible but with that the buttons at 5th,10th,15th,20th and so on gets invisible . i two buttons one with oval white background and other is of green tick mark
    if click on button with tickmark . the button with tick mark gets invisible and if i click on button with oval back ground the tick mark button gets visible.
    Plz help me in this. i just want to know that how to handle this individual clicking .

    thanks in andvance

    ReplyDelete
  41. ...I have two buttons. I cant use the check boxes because when i assign them background.
    the square is getting visible in that back ground which i don't want in my project

    ReplyDelete
  42. This comment has been removed by the author.

    ReplyDelete
  43. I am trying to populate my gridview with data from sqlite query . In my case the number of columns is fixed, but the data for each row is a new query every time. I have seen tutorials where everything is stored into an array and then used and adapter to display in a gridview. Can I do something to only save each row data in an array and keep adding to the gridview display, instead of saving all the rows in a list array?

    My columns have different tourist places and my rows are names of restaurants and I fill the rest of the grids with the distances in between them. Each row value has to be queried from another database and then be displayed after the header (names of tourist places ) has been displayed. It is like a table basically.

    All the tutorials I have seen have a list array defined in resource file or simply add the items and then set adapter. In my case , I cannot add all the data to an array as it will take a lot of memory in my opinion. Any suggestions will be helpful.

    ReplyDelete
  44. Thanks for sharing your knowledge with the world and helping others with your insight. Your blog is a great help to newbies like us . Please keep posting .

    ReplyDelete
  45. hi manish
    i am using gridview as an activity to open some classe , i write the code like you and also wrote setonitemonclicklistener and also an intent , i created a new class that can be open when i will click , but it is not working
    please can u help me as soon as possible
    best regards
    Idma Hoxha

    ReplyDelete
    Replies
    1. I think writing below line into your row.xml will help you for all the item-

      android:focusable="false"
      android:focusableInTouchMode="false"

      Delete
    2. public class MainActivity extends Activity implements AdapterView.OnItemClickListener {
      GridView gridView;
      ArrayList gridArray = new ArrayList();
      CustomGridViewAdapter customGridAdapter;

      @Override
      protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      //set grid view item
      Bitmap newsIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.news);
      Bitmap linkIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.link);
      Bitmap eventsIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.events);
      Bitmap mapIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.map);
      Bitmap libraryIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.library);
      Bitmap scanIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.scan);
      Bitmap shuttlesIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.shuttles);
      Bitmap utaaIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.utaa);
      Bitmap aboutusIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.aboutus);
      Bitmap diningIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.dining);
      Bitmap emergencyIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.emergency);

      gridArray.add(new Item(newsIcon,"News"));
      gridArray.add(new Item(linkIcon,"Link"));
      gridArray.add(new Item(eventsIcon,"Events"));
      gridArray.add(new Item(mapIcon,"Map"));
      gridArray.add(new Item(libraryIcon,"Library"));
      gridArray.add(new Item(scanIcon,"Scan"));
      gridArray.add(new Item(shuttlesIcon,"Shuttles"));
      gridArray.add(new Item(utaaIcon,"UTAA"));
      gridArray.add(new Item(aboutusIcon,"About US"));
      gridArray.add(new Item(diningIcon,"Dining"));
      gridArray.add(new Item(emergencyIcon,"Emergency"));



      gridView = (GridView) findViewById(R.id.gridView1);
      customGridAdapter = new CustomGridViewAdapter(this, R.layout.row_grid, gridArray);
      gridView.setAdapter(customGridAdapter);

      }
      @Override
      public void onItemClick(AdapterView arg0, View arg1, int arg2,long arg3) {
      // TODO Auto-generated method stub




      Intent i = new Intent(getApplicationContext(),ArrayList.class);
      startActivity(i);


      }
      }


      please can you check this code special the onclickitemlistener

      Delete
    3. I am talking about this-

      ImageView android:id="@+id/item_image"
      android:focusable="false"
      android:focusableInTouchMode="false"
      android:layout_width="50dp"
      android:layout_height="50dp"
      android:layout_marginRight="10dp"
      android:src="@drawable/home" >

      And implement your activity with OnItemClickListener remove AdapterView.

      Delete
    4. My xml part is ok
      after i implemented OnItemClickListener, it came this method @Override
      public void onItemClick(AdapterView parent, View view, int position,
      long id) {
      // TODO Auto-generated method stub

      }
      untill here i have got it , but i dont understand intent can u give me a hand , i mean an example of intent ...

      Delete
    5. Have a look on this post-
      http://www.androidhub4you.com/2013/04/sqlite-example-in-android-add-image.html

      Delete
    6. now i took a look on that thing . made me confused :) manish sorry i am disturbing you a lot but
      it is my 4 th day on that thing i am getting creazy , i need a favor from u , can i send this project to your email and check it,
      can you give me your email...or to send in this email manishupacc@gmail.com that i took from a comment that u have done above
      best regards

      Delete
  46. hello sir...you blog has been very helpful to me...thanks a lot for that!!!!

    i am developing an android app which requires the grid view and all that good stuff....

    can u please make a tutorial on how user can create profile in an app(with the field same as any social networking site)...&updating etc....what things(SQLite or SharedPreferences or ) are exactly needed i don't know!!!!

    or should i create a website where this stuff is lot easier and then using JSON & XML parsing i can just pull the data
    from website and then display it in the grid view.....

    would that be a good approach,,...please guide me on this!!

    ReplyDelete
    Replies
    1. I think you need to create a database on server and write web-services for create profile and update profile. And android side just create form and submit data on server.

      Delete
  47. sir can you please explain why you declared RecordHolder as static??? and why used getTag() ????

    ReplyDelete
  48. Thanks u r post is very helpful for me but i want to change the grid image on click that grid item and remain changed as i changed the layout in my app

    ReplyDelete
  49. This comment has been removed by the author.

    ReplyDelete
  50. Hi Manish,
    I am making a custom gridview 3x3 which will be fit to screen and responsive(working properly in different screen sizes).

    Can u help me How to do it

    Thanks .
    Mubin Sayed
    mbnsayed@gmail.com

    ReplyDelete
    Replies
    1. For that you need to maintain res/drawable for all layout- xxhdpi,xhdpi,hdpi,mdpi and for the tablet as well!

      Delete
  51. am getting the following error...
    "the constructor clipdata.item(bitmap string) is undefined"
    any soln?

    ReplyDelete
    Replies
    1. Check Item Class is there constructor item(bitmap string)?

      Delete
  52. Which one is Item class?"CustomGridViewAdapter.java"?No there is no constructor there..i just copy pasted your code!

    ReplyDelete
    Replies
    1. Please download the full code from git repository and copy that Data Object class inside your project.

      https://github.com/manishsri01/CustomGridView

      Delete
    2. ok,thank you manish! and one more thing..i want to display small remainders at the end of imageviews in grid layout as in http://cdn.appstorm.net/android.appstorm.net/files/2011/11/Dashboard1.jpg
      any luck?
      Thanks in advance:-)

      Delete
    3. You can degine your row_grid.xml according to your view, use Frame-layout for that notification item.

      Delete
  53. Q1. Is it possible to put button inside grid view.
    Q2. And in place of toast method can we use intend.
    Is it Possible??
    How?

    ReplyDelete
  54. Q1. Is it possible to put button inside grid view.
    Q2. And in place of toast method can we use intend.
    Is it Possible??
    How?

    ReplyDelete
    Replies
    1. Everything possible, you need to put a button into row.xml, create your view according to your requirement and for the second question-

      Intent myintenintent = new Intent(First.this, Second.class);
      startActivity(myintenintent);

      Delete
  55. Thank you Manish! It's really useful. (^_^)

    ReplyDelete
  56. I want to create a signup form like whatsapp including the profile creation activity from where should I start or from where can I get the code..I am beginner in android.

    ReplyDelete
  57. In Wich Package do you find Class Item????

    ReplyDelete
    Replies
    1. Please extract the zip project and you will find it inside main package-
      com.manish.customgridview

      Delete

  58. I want Dynamic GridView.means i want to set Grid on wifi scanned devices.means if there are 2 wifi devices present then only 2 wifi devices should be shown on screen with geid icon/image.i tried it by static.bt i can't understand how to make it dyname..plz help me.

    ReplyDelete
  59. hello frds gridview data pass in another activity how?

    ReplyDelete
    Replies
    1. Go inside OnItem Click Listener and use Intent to send values to next activity-

      gridView.setOnItemClickListener(new OnItemClickListener() {

      @Override
      public void onItemClick(AdapterView arg0, View v, int position,
      long arg3) {
      Toast.makeText(getApplicationContext(),gridArray.get(position).getTitle(), Toast.LENGTH_SHORT).show();
      Intent intent=new Intent(ActvityA.this,ActivityB.class);
      intent.putExtra("name",title);
      //etc etc
      startActivity(intent);
      }
      });


      Delete
  60. Hello developers ...I have developed an asp.net web application using SQL server 2012..i want to develop an android application and connect it with my asp.net web app..my task is to send and retrieve data by both the android app and asp.net app from the same database...how is it possible..please guide me..

    ReplyDelete
  61. Hi, thank you for tutorial, this is very helpful.
    Maybe it's very simple but I'm new and couldn't figure it out, I need to ask this;
    I'm trying to display image with text in gridView, and also onItemClick I want to explain it with 3 custom text. Something like as a drink 1-"image" 2-"ingredient" 3-"preparetion" could I do something like this.
    How should I edit listArray could you give me a example, thank you very much again.

    ReplyDelete
    Replies
    1. Your need to just modify your row_grid.xml and custom adapter file.

      Delete
  62. I already edit row_grid layout, and lots more. I see 3 lines of text at gridview layout. Gridview must have only image and title. With onitemclick in row_grid layout I want to set image, title, title_ingredient, title_preparation. How can do this?

    ReplyDelete
  63. thank you manish you are a real hero a lifesaver for me thanks a lot for this example i am trying to find solution for this problem for last 3 days and i found it here

    ReplyDelete
  64. getImage() method undefined for the type ClipData.Item Java

    ReplyDelete
  65. i have a error like cannot solve symbol R

    ReplyDelete
  66. can any one tell how to select some item from gridview and share it to another activity or social media.
    pls help me.
    thanks in advance

    ReplyDelete
  67. How to create a gridview this(http://mylearnandroid.blogspot.in/2014/06/android-custom-navigation-drawer-with.html) MainActivity page?. and i click everyone submenu goto new gridview page?.
    It is Possible?.

    ReplyDelete
  68. where is the item class...? the code mentioned above is not working

    ReplyDelete