Wednesday, September 25, 2013

Android Custom GridView Example

Creating a custom  GridView with Text and Image is as easy as Using a Simple GridView.
We need to just have a custom adapter and populate the GridView elements with custom adapter. It is similar to populating a ListView with Custom Adapter.

If you are not familiar with these two concepts follow my blog

Using Android GridView
ListView with  Custom Adapter

In this example I have explained how to  how to make a custom grid with Text and Image and poipulate it's content through Custom Adapter.

Steps:
  • Create Layout
  • Create Cutom Adapter and override it's getView() method.
  • Set the adapter to GridView


Custom GridView

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

   <GridView
        android:id="@+id/gridViewCustom"
        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" />


</RelativeLayout>

grid_row.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/imageView"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginRight="10dp"
        android:src="@drawable/ic_launcher" >
    </ImageView>

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

</LinearLayout>

CustomGridViewMainActivity.java

public class CustomGridViewMainActivity extends Activity
{

   
            GridView gridView;
            GridViewCustomAdapter grisViewCustomeAdapter;
           
          
            @Override
            protected void onCreate(Bundle savedInstanceState)
            {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.main);
                   
                   
                    gridView=(GridView)findViewById(R.id.gridViewCustom);
                    // Create the Custom Adapter Object
                    grisViewCustomeAdapter = new GridViewCustomAdapter(this);
                    // Set the Adapter to GridView
                    gridView.setAdapter(grisViewCustomeAdapter);
                     
                    // Handling touch/click Event on GridView Item

                      gridView.setOnItemClickListener(new OnItemClickListener() {

                       @Override
                       public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
                           String selectedItem;
                           if(position%2==0)
                               selectedItem="Facebook";
                           else
                               selectedItem="Twitter";
                        Toast.makeText(getApplicationContext(),"Selected Item: "+selectedItem, Toast.LENGTH_SHORT).show();
                       
                       }
                      });


               }

}


 GridViewCustomAdapter.java


public class GridViewCustomAdapter extends ArrayAdapter
{
         Context context;
      
   

     public GridViewCustomAdapter(Context context)
     {
             super(context, 0);
             this.context=context;
            
     }
   
     public int getCount()
        {
                     return 24;
        }

     @Override
     public View getView(int position, View convertView, ViewGroup parent)
     {
             View row = convertView;
            
             if (row == null)
             {
                     LayoutInflater inflater = ((Activity) context).getLayoutInflater();
                     row = inflater.inflate(R.layout.grid_row, parent, false);


                     TextView textViewTitle = (TextView) row.findViewById(R.id.textView);
                     ImageView imageViewIte = (ImageView) row.findViewById(R.id.imageView);
                    
                     if(position%2==0)
                     {
                             textViewTitle.setText("Facebook");
                             imageViewIte.setImageResource(R.drawable.facebook);
                     }
                     else
                     {
                             textViewTitle.setText("Twitter");
                             imageViewIte.setImageResource(R.drawable.twitter);
                     }
             }

   
     
      return row;

     }

}
    



 

New Advance Topics:                   Android LiveWallpaer Tutorial
Android ImageSwitcher                    Android TextSwitcher                                Android ViewFlipper
Android Gesture Detector               Handling/Detecting Swipe Events                Gradient Drawable
Detecting Missed Calls                    Hide Title Bar                                           GridView Animation
Android AlarmManager                 Android BootReceiver                       Vibrate Phone In a Desirable Pattern    
Developing for Different Screen Sizes           Showing Toast for Longer Time       Publishing your App
How to publish Android App on Google Play
Android TextWatcher                               Android ExpandableListView

 Beginning With Android
      Android : Introduction(What is Android)                                                              Configuring Eclipse for Android Development
     Creating Your First Android Project                                           Understanding Android Manifest File of your android app

 Advance Android Topics                                                              Customizing Android Views


Working With Layouts                                                                Working With Views

Understanding Layouts in Android                                                   Using Buttons and EditText in Android
Working with Linear Layout (With Example)                                     Using CheckBoxes in Android
Nested Linear Layout (With Example)                                              Using AutoCompleteTextView in Android                                                                                          Grid View
Relative Layout In Android                                                               ListView
Table Layout                                                                                   Android ProgressBar
Frame Layout(With Example)                                                          Customizing ProgressBar
Absolute Layout                                                                             Customizing Radio Buttons
Grid Layout                                                                                    Customizing Checkboxes In Android

Android Advance Views
Android Spinner                                                                           Android GalleryView
Android TabWidget                                                                      Android ExpandableListView

Android Components                                                                 Dialogs In Android

Activity In Android                                                                    Working With Alert Dialog
Activity Life Cycle                                                                    Adding Radio Buttons In Dialog
Starting Activity For Result                                                       Adding Check Boxes In Dialog
Sending Data from One Activity to Other in Android                    Creating Customized Dialogs in Android
Returning Result from Activity                                                   Creating Dialog To Collect User Input
Android : Service                                                                     DatePicker and TimePickerDialog
BroadcastReceiver                                                                   Using TimePickerDialog and DatePickerDialog In android

Menus In Android                                                                ListView:
Creating Option Menu                                                               Populating ListView With DataBase
Creating Context Menu In Android                                              Populating ListView with ArrayList
                                                                                               ListView with Custom Adapter

Toast                                                                                      Working With SMS
Customizing Toast In Android                                                       How to Send SMS in Android
Customizing the Display Time of Toast                                        How To Receive SMS
Customizing Toast At Runtime                                                  Accessing Inbox In Android
Adding Image in Toast
Showing Toast for Longer Time


TelephonyManager                                                            Storage: Storing Data In Android
Using Telephony Manager In Android                                          SharedPreferences In Android
                                                                                              Reading and Writing files to Internal Stoarage

Working With Incoming Calls                                       DataBase :  Introduction of SQLiteDataBase
How To Handle Incoming Calls in Android                                Working With Database in Android
How to Forward an Incoming Call In Android                            Creating Table In Android
CALL States In Android                                                          Inserting, Deleting and Updating Records In Table in Android


Miscellaneous
Notifications In Android
How To Vibrate The Android Phone
Sending Email In Android
Opening a webpage In Browser
How to Access PhoneBook In Android
Prompt User Input with an AlertDialog
How to Hide Title Bar In Android
How to show an Activity in Landscape or Portrait Mode only.
How to Set an Image as Wallpaper.






55 comments:

  1. thanks kamlesh for such useful tutorial..
    i really want grid view tutorial.

    ReplyDelete
  2. good article, thankyou
    please visite back my blog
    beliatekno.blogspot.com

    ReplyDelete
  3. hey.. nice tutorial.. can u please tell me how to implement custom grid view in fragments.. ? thanks in advance.

    ReplyDelete
    Replies
    1. I've been exploring and experimenting to make gridview in fragment for almost 2 weeks now, but so far I'm in vain. No luck!

      Delete
  4. nice tutorial.. I'm implementing Custom Grid View in fragments. But I'm unable to bind the custom view / layout to the grid view using code.

    ReplyDelete
  5. hey Kamlesh Yadav,
    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
  6. Nice tutorial. Can u please explain detail implementation of Grid view in fragments

    ReplyDelete
  7. Thanks for the detailed instruction. We create mobile apps based on android. For more info visit our website.

    ReplyDelete
  8. Its extremely instructive, intelligent and quality substance. I wish all of you good fortunes for your coming sites and posts. Continue sharing! blog live

    ReplyDelete
  9. Nice Article. I have read whole article and I like the examples.maybe even make a sticky post if it's getting a lot of engagement.
    Graphic Design Contest

    ReplyDelete
  10. You can definitely see your enthusiasm in the work you
    write. The arena hopes for more passionate writers like
    you who aren't afraid to mention how they believe.
    Always follow your heart.

    ReplyDelete
  11. Hello fantastic blog! Does running a blog such as this require a massive amount work?
    I have no expertise in computer programming however I had
    been hoping to start my own blog soon. Anyway, if you have any
    ideas or tips for new blog owners please share. I know this is off subject nevertheless I just wanted
    to ask. Many thanks!

    ReplyDelete
  12. What's up, everything is going well here and ofcourse every one is sharing information, that's actually fine,
    keep up writing.

    ReplyDelete
  13. Ƭhiѕ paragraph օffers сlear idea for the new visitors of blogging, tһat in fаct һow tо Ԁo
    blogging аnd site-building.

    ReplyDelete
  14. Right here iѕ the right web site for ɑnyone who wishes t᧐ understand tһis topic.
    Yоu кnoԝ ѕo mucһ its almost tough to argue witһ
    you (not tһat I really woulⅾ wɑnt to?HaHa). You definitely рut a fresh spin on a topic tһat has been diѕcussed f᧐r ages.
    Excellent stuff, just wonderful!

    ReplyDelete
  15. I'm really enjoying the theme/design of your site.
    Do you ever run into any web browser compatibility problems?

    A handful of my blog audience have complained about my blog
    not working correctly in Explorer but looks great in Chrome.
    Do you have any advice to help fix this problem?

    ReplyDelete
  16. Keep on writing, great job!

    ReplyDelete
  17. I'm impressed, I must say. Seldom do I come across a blog
    that's equally educative and amusing, and let me tell you,
    you have hit the nail on the head. The issue is something that not enough people are speaking intelligently
    about. I am very happy that I came across this during my hunt for something concerning this.

    ReplyDelete
  18. Ꮋi there! I could have sѡorn I've been to this site before but after browsing
    tһrough some of the post I realiᴢed it's new
    to me. Anyways, I'm definitely hapρy I found it and I'll be book-marking and checking back frequently!

    ReplyDelete
  19. Ι was recommended tһis website by my cousin. I'm not sսre whether thіs post is written by him as noƄody else know such dеtailed about
    my difficulty. You're wonderful! Thanks!

    ReplyDelete
  20. Spot on ᴡith this write-սρ, I honestly believe that thiѕ site needs a great deal
    more attention. I?ll probably be back again to see more,
    thanks for the info!

    ReplyDelete
  21. I lіke this web site it's a master piеce! Glad I
    disⅽovered this on google.

    ReplyDelete
  22. Ꮋey there, You've performed ɑn іncredible job. I'll certainly digg it and in my
    opinion recommend to my friends. I'm confident theʏ'll be benefited from this web sitе.

    ReplyDelete
  23. Do yoᥙ have a spam іssuе on this site; I also am a blogger, and I was curious about your sitᥙation; many ߋf uѕ have developeⅾ some nice methoɗs and wе are
    looking to еxchange solutions with others, Ьe sure to sho᧐t me an e-mail if іnterested.

    ReplyDelete
  24. Ꭼxcellent blog riցht here! Additiοnally your wеb site so much up faѕt!

    What web host are you the ᥙsage of? Can I am getting your affiliate hyperlink in yߋur host?

    I wish my website loaded up as quickly as yours lol

    ReplyDelete
  25. Hellο, Neat post. Tһere is an issue with your website in web explorer, may cheсk this...
    IE still is tһe market chief and a large component to folks ѡill pasѕ over your excellent writing due to
    this problem.

    ReplyDelete
  26. Someone necesѕaгily lend a hand to make severely articlеs I'd state.

    That is the very first time I frequented your web page and thus
    far? I surprised with the research you made to make this actual publish incredible.

    Great activity!

    ReplyDelete
  27. Howdу just wаnted to gіve you a quick heads up and let
    you know а feԝ of the pictures aren't loading correctly.
    I'm not sure why but I thіnk its a linking isѕue.
    I've tried it in two dіfferent web browsers and both
    show the same outcomе.

    ReplyDelete
  28. You made a few nice points there. I did a search on the matter and found most ⲣeople ԝill have the same opinion with your blog.

    ReplyDelete
  29. Ӏ conceive this site has verу excellent pent written content articles.

    ReplyDelete
  30. I tһink other website owners should takе this internet site as
    an model, very clean and superb user genial layout.

    ReplyDelete
  31. Noгmally I don't read article on blogs, however I wish to saу that this wгite-up very pressured me to try and do it!
    Your writing taste has been amɑzed mе. Thanks, very ɡreat
    post.

    ReplyDelete
  32. That іs very attentіon-grabbing, You're an excessively skіlled blogger.
    I've joined your rss feed and ⅼook forward to in the hunt for extra of your magnifіcent post.
    Also, I have shareԁ your site іn my social netѡorks

    ReplyDelete
  33. Ηi, i rеad yⲟur blog occasionally and i own a
    similar one ɑnd i was just curious if you get a lot of
    spam remarks? If so how do you stop it, any plugin or anythіng
    you can recommend? I get so much lately it's driνing
    me mad so any suрport іs very much aрpreciatеԀ.

    ReplyDelete
  34. ceгtainly like your websіte but you need to take a look at the spelling on several of
    your posts. A number of tһem are rife with spelling
    issues and I find it very troublesome to tell the reality however I'll surelʏ
    come again again.

    ReplyDelete
  35. Incredible! Thіs ƅlog looks just like my old one!
    It's on a totally different topic but it has pretty much the same page layout
    and design. Excellent choice of ϲolors!

    ReplyDelete
  36. І am thankful that I found tһis web ѕite, exactly the right information that I
    was looking for!

    ReplyDelete
  37. Aftеr exploring a handful of thе blog posts on your website, I
    гeally like your way of blogging. I savеd it to my Ьookmaгk website list and will be
    checking back in the near futurе. Please visіt
    my web site too and let me know what you think.

    ReplyDelete
  38. After exploring a few of the blߋg articles on yߋur web site,
    I seriousⅼy like your way of writing a blog. I book-marked it to my bookmark wеbpage list and
    will be checking back soon. Please check out my website
    as well and tell me what yоu think.

    ReplyDelete
  39. I am tһankful that I notіced this web site, jᥙst the right info tһat I was looking for!

    ReplyDelete
  40. Wow, this article iss good, my younger sister is analyzibg such things, so I am going to tell her.

    ReplyDelete
  41. I constantly spent my half an hour to read this
    web site's content everyday along with a cup of coffee.

    ReplyDelete
  42. Hello tto all, how is all, I think every one is getting more from this website, and your views are
    good in support of new people.

    ReplyDelete
  43. well, monetizing websites and stuffs should be great. making money on the internet is a great way to earn money“ best place to buy instagram likes

    ReplyDelete
  44. Aw, this was a very good post. In notion I have to devote writing like that moreover – taking time and actual effort to manufacture a great article… but what can I say… I procrastinate alot and by no indicates apparently go accomplished. 토토사이트

    ReplyDelete
  45. My dear goodness! an amazing article guy. Many thanks Nevertheless I’m going through problem with third really simply syndication . Have no idea exactly why Unable to subscribe to that. Will there be anybody acquiring comparable rss or atom downside? Anyone who knows generously reply. Thnkx Kevin David Scam

    ReplyDelete
  46. Managing a business Instagram account is another task on your to-do list that's already packed with meetings, deadlines and projects. Savedelete.com

    ReplyDelete
  47. customers use social media channels to find information about any business. That means your role as a business owner should be to maintain your brand's online presence. Homebusinessmag

    ReplyDelete
  48. Hi,
    Thanks for sharing the information with us it was very informative. https://hangup.in

    ReplyDelete