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.






54 comments:

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

    ReplyDelete
  2. 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
  3. 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
  4. 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
  5. Nice tutorial. Can u please explain detail implementation of Grid view in fragments

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

    ReplyDelete
  7. 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
  8. 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
  9. 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
  10. 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
  11. What's up, everything is going well here and ofcourse every one is sharing information, that's actually fine,
    keep up writing.

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

    ReplyDelete
  13. 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
  14. 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
  15. Keep on writing, great job!

    ReplyDelete
  16. 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
  17. Ꮋ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
  18. Ι 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
  19. 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
  20. I lіke this web site it's a master piеce! Glad I
    disⅽovered this on google.

    ReplyDelete
  21. Ꮋ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
  22. 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
  23. Ꭼ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
  24. 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
  25. 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
  26. 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
  27. 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
  28. Ӏ conceive this site has verу excellent pent written content articles.

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

    ReplyDelete
  30. 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
  31. 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
  32. Η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
  33. 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
  34. 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
  35. І am thankful that I found tһis web ѕite, exactly the right information that I
    was looking for!

    ReplyDelete
  36. 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
  37. 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
  38. I am tһankful that I notіced this web site, jᥙst the right info tһat I was looking for!

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

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

    ReplyDelete
  41. 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
  42. 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
  43. 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
  44. 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
  45. 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
  46. 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
  47. Hi,
    Thanks for sharing the information with us it was very informative. https://hangup.in

    ReplyDelete