Dilip Dilip - 1 year ago 591
Android Question

How to put GridView inside ScrollView

I have to design layout such that whole layout should scroll and inside layout I have to display related content in

form so I decided to use
.But problem is that I’m unable to use
I have read documentation(Documentation also saying that we should not use
) also.But I have to do this,so can any please give me some idea about this.Thanks

Answer Source

There are definitely benefits to a GridView beside the inherent scrolling. For example, a consistent, dynamic layout of cells that will expand and contract based on the data you pass into it. So, when people say it's not good to desire such a functionality, I think that's wrong because you could want the dynamic grid of images (views) inside of a scrolling view, but want that entire scrolling view to contain other things than just the grid cells.

Now, here is how you can do this. Check the answer here. It is an expandable height GridView, which you will want to import / create in your project. What that basically means is that as more items are added to the GridView, it will just expand its height, as opposed to keeping its height set and using scrolling. This is exactly what you want.

Once you have the ExpandableHeightGridView in your project, go to your XML layout where you want the GridView to be. You can then do something like this (paraphrasing):

<ScrollView ...>
    <RelativeLayout ...>
        <com.example.ExpandableHeightGridView ... />
        <other view items />

Then, in your activity where you set the GridView's adapter, you want to make sure you set it to expand. So:

ExpandableHeightGridView gridView = (ExpandableHeightGridView) findViewById(R.id.myId);

The reason you want this expandable GridView is because, the fact that a standard GridView doesn't expand is what causes it to scroll. It sticks to a certain height, and then as more items fill it past its view bounds, it becomes scrollable. Now, with this, your GridView will always expand its height to fit the content within it, thus never allowing it to enter its scrolling mode. This enables you to use it inside of the ScrollView and use other view elements above or below it within the ScrollView, and have them all scroll.

This should give you the result you're looking for. Let me know if you have any questions.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download