Android listview inside scrollview

ListView внутри ScrollView

В работе над проектом возникла необходимость отрисовать лейаут такого вида: сверху компактным блоком располагаются детали топика, а под ними – список комментариев к этому топику. Сначала оно было реализовано естественным образом: лейаут деталей топика, а под ним – список. Позже ТЗ поменялось, и получилось, что нужно заголовок скролить вместе со списком.

Первым побуждением было сделать то, что вынесено в заголовок: поместить ListView внутрь ScrollView. Получившаяся штука отображалась некорректно, что заставило меня зарыться поглубже в гугл.

Во многих местах в сети (например, тут: https://groups.google.com/forum/#!topic/android-beginners/LRpLgGOy2Pc или тут: http://stackoverflow.com/questions/1526831/android-scrollview-layout-problem) напрямую говорится о том, что так делать нельзя. Для реализации таких вещей у ListView предусмотрены штатные заголовки (headers).

Добавление заголовков производится вызовом метода класса ListView:

где View v можно создавать любым способом (или явным вызовом конструктора, или через inflater).

View hv = . ;
listView.addHeaderView(hv);

Заголовков у ListView может быть больше одного. С их количеством, кстати, связана ещё одна особенность: по умолчанию заголовки тоже кликабельны, как и обычные элементы списка, клик на них вызывает отработку лиснеров, заданных вызовами setOnItemClickListener и setOnItemLongClickListener, так что позиция кликнутого элемента, которая передаётся в лиснеры в параметре position, будет смещена на количество заголовков. Этот факт нужно обязательно учитывать в лиснерах при обработке. Для этого у ListView есть метод:

который возвращает количество заголовков списка. На значение, которое он возвращает, можно, например, уменьшить значение position, полученное в лиснере, перед позиционированием во внутреннем списке данных.

protected OnItemClickListener itemClickListener = new OnItemClickListener() <
public void onItemClick(final AdapterView l, final View v, final int position, final long id) <
MyItem myItem = myItems.get(position — listView.getHeaderViewsCount());
// do something to myItem
>
>;

Существует ещё один метод для добавления заголовков, чуть более сложный:

Он предоставляет возможность сделать заголовок некликабельным: если в третий параметр передать false, то при клике на заголовок не будет отрабатывать onItemClickListener списка. Лиснеры же, заданные для views, расположенных внутри такого заголовка, будут отрабатывать штатно. Однако, даже в этом случае, несмотря на некликабельность заголовка, нумерация элементов для position всё равно будет учитывать их наличие.

View hv = . ;
listView.addHeaderView(hv, null, false);

Для полноты изложения скажу, что вторым параметром (Object data), смысл которого не очень понятен из документации, на самом деле задаются данные, которые будут возвращаться методом Adapter.getItem() (взято тут: http://stackoverflow.com/questions/4311693/what-does-the-second-parameter-in-addheaderview-in-the-class-listview-do).

Аналогичный набор методов есть у списка и для футеров (footers):

Источник

The Developer World Is Yours

The best place for Magento & Android tips and tricks… and much more!

Expandable Listview inside scrollview

When we have a ListView expandable inside ScrollView, we must make this in our layout, always expandable listview must be the last view in our layout:

Читайте также:  Как сделать чтобы тебе не могли звонить андроид

In your onCreate

You need this function:

44 thoughts on “ Expandable Listview inside scrollview ”

This solution worked , thanks .

Well done 🙂
it worked for me thanks saved my day. 🙂

Hello
it is working for me but i tried to understand the content of the function setListViewHeight but i didn’t understand it
please if u have time to explain what u are doing in it i will be very happy
thank u in advance

Hi. of course.
I hope that my explanation will help you

The first step, we create variable height and width.

for each group we add group’s height.

if group is expandable, for each item we add item’s height.

LayoutParams are used by views to tell their parents how they want to be laid out. See ViewGroup Layout Attributes for a list of all child view attributes that this class supports.

Then we add divider height * number of group and we get total height in List.

getDividerHeight ()
Returns the height of the divider that will be drawn between each item in the list.

Now we check the minimum.

we add height to params

the last line we use
requestLayout()
Call this when something has changed which has invalidated the layout of this view.

Try to Make it in c# xamarin it will be great help for me.

Thanks for the code. It works great once the group item is clicked but it only shows one group item initially. Any help is appreciated!

It works fine for me .

But I have a problem in my case I don’t want to re-create activity on orientation change so I restrict it through manifest file so resolution specification I calculated in portrait mode reflected in landscape also , that’s why when I rotate my device it shows extra space in after last child .

Thanks in advance 🙂

A lot of thanks. Its working perfectly. Really nice .
Thanks again.

If you want to set height of exp. listview, when activity will start, you can use this function:
setListViewHeightForGroups(your_expList_AfterAcceptingAdapter);

This is not worked for me. please help me

This code should work. Which is your error?

NO error. calculating wrong height. For E.g If Actual height is 2378 but it’s 3500
But i click on expand it is working fine.

Worked!! Great work.

Is this condition right?

if (((listView.isGroupExpanded(i)) && (i != group))
|| ((!listView.isGroupExpanded(i)) && (i == group))) <

Seems like its never satisfies the condition.

oh, i got it, i was using in groupexpand and not on groupclick. i changed the condition, so its working on groupexpand

Thank you so much.

Thank you for this nice solution !

I just have an issue, I set android:dividerHeight=”5dp” in my ExpandableListView but when doing that I only see the first item.

What did I miss ?

Maybe because Android can´t calculate height when you set dividerHeight. Android is not perfect.

Thanks! It works (almost).

However , it only works after you click on a group item.
What about when you just open the layout and haven’t opened any group item?

Читайте также:  Что такое unity для android

Источник

ListView внутри ScrollView

Если вы разрабатываете под Андройд, то наверняка сталкивались с задачей заставить ListView растягиваться по высоте своего контента, например чтобы поместить его внутрь ScrollView вместе с другими элементами. На самом деле подобный подход не рекомендуется использовать, т.к. ListView создавался не для этого, но мы не ищем легких путей и иногда проще «тупо сделать вот так».

Первое решение которое приходит в голову: назначить высоту wrap_content для ListView. Это не работает. Можете даже не пробовать, максимум чего вы добьетесь это растяжения высоты на первый элемент списка.

После еще некоторых попыток заставить список тянуться по высоте начинается гугление. К сожалению, гугл не выдает конкретного ответа на вопрос, только наводки и предложения. Все сводится к тому, чтобы вручную измерять общую высоту элементов списка и назначать списку сумарную высоту. Если вы хорошо разбираетесь в Андройде, наверное, это не будет проблемой, а для таких как я предлагаю готовое решение, честно найденное на просторах StackOverflow:

Этот метод нужно вызвать на нашем ListView после заполнения всех элементов. Все проверено и работает в Android 4.0+ (API 14+). На более ранних версиях честно не проверял, но думаю проблем быть не должно.

Есть еще один мелкий момент, который возможно кому-то пригодится. Если у вас используются разделители списка (divider), то нужно заменить одну строчку на это:

Источник

Flutter : ListView, GridView inside ScrollView

Dec 12, 2018 · 3 min read

Sometimes you need to use a ListView or GridView inside a ScrollView (SingleChildScrollView). We know this isn’t a good practise as you can’t put a ListView being a Scrollable widget inside ScrollView, but for some reason i wanted to achieve this, especially when i want to show both ListView and GridView at the same time.

First of all, let’s see what happens when you put a ListView inside a SingleChildScrollView.

Create a new project and embed the following code:

The HeaderWidget and BodyWidget are just simple widgets. (These are separated just to maintain the readability of the code)

If you run the above code, you get an exception in the console.

Note the bold text above.
The gist of which says that you can’t place an unbounded height widget (ListView, GridView) inside a Scrollable widget.

So how do we implement it?

Here we’ll be using Slivers to achieve this. Read more about slivers over here.

Replace the above code with the following code:

In the above code:

1. We are replacing SingleChildScrollView with CustomScrollView.

2. Using SliverList in place of Column for showing HeaderWidget.

3. Finally using grid with SliverGrid.

Here’s the outcome of this:

Cool enough! We have both TextWidget, ListView, GridView inside that of ScrollView.

Note that your ListView, GridView must not have large number of children which can affect the scrolling performance as both of these widget do not inflate all children at the same time.

Whola! Both you and I learnt something new today. Congrats
Clap! Clap! Clap!

The Flutter Pub is a medium publication to bring you the latest and amazing resources such as articles, videos, codes, podcasts etc. about this great technology to teach you how to build beautiful apps with it. You can find us on Facebook, Twitter, and Medium or learn more about us here. We’d love to connect! And if you are a writer interested in writing for us, then you can do so through these guidelines.

Читайте также:  Android terminal emulator imei

Источник

How to Make Android ListView or GridView Expandable inside ScrollView

We all know that placing a ListView or GridView inside ScrollView will make them becoming difficult to scroll and can not be expanded. Android doesn’t provide a built in API to handle this problem so we have to do a little hack by subclassing those two views.

This is hack i found on stackoverflow, from Neil Traft ‘s answer:

ExpandableHeightListView

ExpandableHeightGridView

How to use:

As you can see, to make the ListView or GridView expandable, just call the setExapanded(true).

About Lorensius Londa

Passionate web and mobile application developer. Co-founder of TRUSTUDIO, loves programming, Android, aviation, travelling, photography, coffee and gym mania.

Reader Interactions

Comments

Igor Ganapolsky says

This approach works for GridView inside a ScrollView. Thanks for the workaround!

Hello,
very nice video!
i want to make exact same as shown in your video.
Can you provide some resources that can help me do it.
I use web service to fetch images and want to display them like google play , one big in 1st row, 2 smaller in 2nd row and so..
I bit confused with the appropriate layout files

Thanks in advance

Yash Tripathi says

hello i am new in android development and i placed this code

ExpandableHeightListView listView = new ExpandableHeightListView(this);

inside oncreate method but its not work for me please help me and provide full code of this example

Nilay Sheth says

Very Good tutorial Thanks a lot bro. Can you also add the source code in this tutorial too ?

Does this work also on ExpandableListView?

Mahmoud ELshamy says

Thank you, It helped me so much.

I m facing the problem in this when i implement onitemclick listner. i mean its not working which u given example

can u plz tell me how to do that?

Thnak You Very Much.

Archish Thakkar says

Please provide me download link of source code. I need source code.

Thanking You,
Archish Thakkar

Archish Thakkar says

Please provide download link of the following code.I need source code.

Giorgio Zamparelli says

Hi, thanks for the post.
When I add many items to the ExpandableHeightGridView the scrollbar is automatically scrolled down.
Anyway to avoid this?

morteza Amzajerdi says

Thank you , that was very useful.

I have some checkbox in custom grid view , But it is not showing full content last row is not visible , could you please help?

Sarith NOB says

Oh my god!
Your post save much my time, whenever I don’t know about it even a little bit.

Thank you very much!

Leave a Reply Cancel reply

Primary Sidebar

About Me

A husband, father of two, passionate software developer, diy lover and home baker who loves to learn new things. Read More…

Источник

Оцените статью