Scrolling in listview android

How to make android listview scrollable?

I have two listviews, but they don’t scroll. How do I correct this?

Here is my layout.xml

10 Answers 10

Never put ListView in ScrollView . ListView itself is scrollable.

By default ListView is scrollable. Do not put ScrollView to the ListView

Practically its not good to do. But if you want to do like this, just make listview’s height fixed to wrap_content.

I know this question is 4-5 years old, but still, this might be useful:

Sometimes, if you have only a few elements that «exit the screen», the list might not scroll. That’s because the operating system doesn’t view it as actually exceeding the screen.

I’m saying this because I ran into this problem today — I only had 2 or 3 elements that were exceeding the screen limits, and my list wasn’t scrollable. And it was a real mystery. As soon as I added a few more, it started to scroll.

So you have to make sure it’s not a design problem at first, like the list appearing to go beyond the borders of the screen but in reality, «it doesn’t», and adjust its dimensions and margin values and see if it’s starting to «become scrollable». It did, for me.

You shouldn’t put a ListView inside a ScrollView because the ListView class implements its own scrolling and it just doesn’t receive gestures because they all are handled by the parent ScrollView

Listview so have inbuild scrolling capabilities. So you can not use listview inside scrollview. Encapsulate it in any other layout like LinearLayout or RelativeLayout.

This is my working code. you may try with this.

employee bean class:

in Activity class:

Putting ListView inside a ScrollView is never inspired. But if you want your posted XML-like behavior, there’re 3 options to me:

Remove ScrollView : Removing your ScrollView , you may give the ListView s some specific size with respect to the total layout (either specific dp or layout_weight ).

Replace ListView s with LinearLayout s: You may add the list-items by iterating through the item-list and add each item-view to the respective LinearLayout by inflating the view & setting the respective data (string, image etc.)

If you really need to put your ListView s inside the ScrollView , you must make your ListView s non-scrollable (Which is practically the same as the solution 2 above, but with ListView codes), otherwise the layout won’t function as you expect.
To make a ListView non-scrollable, you may read this SO post, where the precise solution to me is like the one below:

Источник

Android getting exact scroll position in ListView

I’d like to get the exact, pixel position of the ListView scroll. And no, I am not referring to the first visible position.

Is there a way to achieve this?

Читайте также:  Карты россии для навитела android

8 Answers 8

Okay, I found a workaround, using the following code:

The way it works is it takes the actual offset of the first visible list item and calculates how far it is from the top of the view to determine how much we are «scrolled into» the view, so now that we know that we can calculate the rest using the regular getFirstVisiblePosition method.

Saarraz1’s answer will only work if all the rows in the listview are of the same height and there’s no header (or it is also the same height as the rows).

Note that once the rows disappear at the top of the screen you don’t have access to them, as in you won’t be able to keep track of their height. This is why you need to save those heights (or accumulated heights of all). My solution requires keeping a Dictionary of heights per index (it is assumed that when the list is displayed the first time it is scrolled to the top).

Simplest idea I could come up with was to extend ListView and expose the «computeVerticalScrollOffset» which is protected by default, then use «com.your.package.CustomListView» in your xml layouts.

First Declare your int variable for hold the position.

then add scrollListener to your ListView,

Then after getting new data or any changes in your data that time you need to set the listview current position

I have used after setup my adapter , works fine for me..

If anyone else found this in Google while looking for a way to track relative scroll offsets in an OnScrollListener — that is, change in Y since the last call to the listener — here’s a Gist showing how to calculate that.

I know I’m late to the party but I felt like sharing my solution to this problem. I have a ListView and I was trying to find how much I have scrolled in order to scroll something else relative to it and cause a parallax effect. Here’s my solution:

I created my own OnScrollListener where the method onScrollPositionChanged will be called every time onScroll gets called. But this method will have access to the calculated value representing the amount that the ListView has been scrolled.

To use this class, you can setOnClickListener to a new OnScrollPositionChangedListener and override the onScrollPositionChanged method.

Источник

Полный список

— рассматриваем события ListView: нажатие — onItemClick, выделение — onItemSelect, прокрутка — onScroll

При взаимодействии со списком может возникнуть необходимость обрабатывать события – нажатие на пункт и прокрутка. Попробуем это сделать.

Создадим проект:

Project name: P0441_SimpleListEvents
Build Target: Android 2.3.3
Application name: SimpleListEvents
Package name: ru.startandroid.develop.p0441simplelistevents
Create Activity: MainActivity

Нарисуем экран main.xml:

На экране только ListView.

Так же, как и на прошлом уроке добавим список имен в ресурс res/values/strings.xml:

Пишем код MainActivity.java:

Смотрим код. Мы находим экранные элементы, создаем и присваиваем списку адаптер. Далее списку мы присваиваем два обработчика событий:

1) OnItemClickListener – обрабатывает нажатие на пункт списка

parent – View-родитель для нажатого пункта, в нашем случае — ListView
view – это нажатый пункт, в нашем случае – TextView из android.R.layout.simple_list_item_1
position – порядковый номер пункта в списке
id – идентификатор элемента,

Читайте также:  Увеличение внутренней памяти android за счет sd карты xiaomi redmi

Мы в лог будем выводить id и position для элемента, на который нажали.

2) OnItemSelectedListener – обрабатывает выделение пунктов списка (не check, как на прошлом уроке)

Предоставляет нам метод , android.view.View, int, long)» target=»_blank»>onItemSelected полностью аналогичен по параметрам методу onItemClick описанному выше. Не буду повторяться.

Также есть метод )» target=»_blank»>onNothingSelected – когда список теряет выделение пункта и ни один пункт не выделен.

Все сохраним и запустим приложение.

Ткнем какой-нибудь элемент, например — Петр. Смотрим лог:

itemClick: position = 2, >

Все верно. Т.к. позиция считается не с единицы, а с нуля – Петр имеет позицию 2. (В нашем случае id равен position. Я пока не встречал случаев id != position, но наверняка они есть)

Теперь покрутите колесо мышки или понажимайте клавиши вверх вниз на клавиатуре. Видно что идет визуальное выделение элементов списка.

А в логах мы видим такие записи:

itemSelect: position = 2, > itemSelect: position = 3, > itemSelect: position = 4, > itemSelect: position = 5, > itemSelect: position = 4, > itemSelect: position = 3, > itemSelect: position = 2, >

Т.е. обработчик фиксирует какой пункт выделен. Честно говоря, я не очень понимаю как можно использовать такое выделение. Но обработчик для него есть и я решил про него рассказать. Пусть будет.

Снова нажмем теперь на любой пункт списка, мы видим, что выделение пропало. Логи:

itemSelect: nothing
itemClick: position = 3, >

Ничего не выделено и нажат пункт с позицией 3.

Давайте добавим к списку еще один обработчик:

OnScrollListener – обрабатывает прокрутку списка.

view – это прокручиваемый элемент, т.е. ListView
scrollState – состояние списка. Может принимать три значения:

SCROLL_STATE_IDLE = 0, список закончил прокрутку
SCROLL_STATE_TOUCH_SCROLL = 1, список начал прокрутку
SCROLL_STATE_FLING = 2, список «катнули», т.е. при прокрутке отпустили палец и прокрутка дальше идет «по инерции»

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

view – прокручиваемый элемент
firstVisibleItem – первый видимый на экране пункт списка
visibleItemCount – сколько пунктов видно на экране
totalItemCount – сколько всего пунктов в списке

Причем для параметров firstVisibleItem и visibleItemCount пункт считается видимым на экране даже если он виден не полностью.

Все сохраним и запустим.

Теперь потаскайте список туда-сюда курсором (как будто пальцем) и смотрите логи. Там слишком много всего выводится. Я не буду здесь выкладывать. Но принцип понятен – меняется первый видимый пункт (firstVisibleItem) и может на единицу меняться кол-во видимых пунктов (visibleItemCount).

Теперь закоментируем вывод в лог в методе onScroll (чтобы не спамил нам лог) и раскаментим в onScrollStateChanged.

Схватим список, немного потягаем туда сюда и отпустим. Смотрим лог:

scrollState = 1
scrollState = 0

Отработали два события – список начал прокрутку, список закончил прокрутку.

Попробуем взять список, «катнуть» его и отпустить.

scrollState = 1
scrollState = 2
scrollState = 0

Видим три события – прокрутка началась, список «катнули», прокрутка закончилась.

Полный код урока:

На следующем уроке:

— строим список-дерево ExpandableListView

Присоединяйтесь к нам в Telegram:

— в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.

Читайте также:  Ai box android через carplay

— в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Kotlin, RxJava, Dagger, Тестирование

— ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня

— новый чат Performance для обсуждения проблем производительности и для ваших пожеланий по содержанию курса по этой теме

Источник

Listview Scroll to the end of the list after updating the list

I would like to make sure that the list is scrolled all the way to the bottom, after I have updated the listview by using listAdapter, so that it displays the last element entered in the list. How can I do this ?

I tried this but no luck:

9 Answers 9

Supposing you know when the list data has changed, you can manually tell the list to scroll to the bottom by setting the list selection to the last row. Something like:

You need to use these parameters in your list view:

Set the head of the list to it bottom lv.setStackFromBottom(true);

You can also set these parameters in XML, eg. like this:

A combination of TRANSCRIPT_MODE_ALWAYS_SCROLL and setSelection made it work for me

I’ve had success using this in response to a button click, so I guess that you can use it too after updating your contents:

To get this in a ListFragment:

Added this answer because if someone do a google search for same problem with ListFragment he just finds this..

Using : Set the head of the list to it bottom lv.setStackFromBottom(true);

Worked for me and the list is scrolled to the bottom automatically when it is first brought into visibility. The list then scrolls as it should with TRANSCRIPT_MODE_ALWAYS_SCROLL .

Источник

ListView is not scrolling inside NestedScrollView in android

I’ve inflated a fragment from view pager which uses the listview. And list view does not support setNestedScrollingEnabled in pre lollipop devices. So I’ve added the listview inside a NestedScrollView but when scrolling the list it does not scrolling.

Can anyone suggest me any solution. Thanks in advance.

8 Answers 8

Use ViewCompat.setNestedScrollingEnabled() and your problem will be solved.

I am not sure why you would want to use a ListView inside a ScrollView if it will take up the entire height/width of it’s parent.

I would suggest just using the ListView in the root layout of your fragment and eliminate the ScrollView.

Also, I would suggest using RecyclerView instead of ListView as it implements NestedScrollingChild.

But if you are set on having nested scroll views in your layout you need to understand that NestedScrollView is intended to work as parent or a child scroll view while list. Here is a good example of a scrollview containing 2 other scrollviews:

Also, I noticed that you are maybe using CoordinatorLayout because you are setting the layout behavior of your child views. If so, you only need to specify the ‘app:layout_behavior=»@string/appbar_scrolling_view_behavior»‘ for your main and only ScrollView: A ListView, RecyclerView or NestedScrollView.

Источник

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