How to make the list scroll through until the last item is on top of the screen

I am developing an application that should show the calendar as an agenda in my own calendar. I have a list showing different events (Note: in the context of the question, this is an object of my system). I want to provide the Today button on this screen. When the user clicks on this button, the events should be scrolled until the first event of the current schedule is on top of the screen. The problem arises when I have only a few events planned from today - so few that they do not fill the entire screen. Then the list view simply scrolls until the last event in the calendar is at the bottom. This usually means that the desired effect from today's first event at the top is not achieved.

Any suggestions how to do this? I thought about adding some elements to the end, but this seems like an ugly workaround, and in addition, it will require special calculations for a particular device, which will tell me how many elements need to be inserted.

Edit :
Adding some code as requested in the comment
Actually, I'm not sure if this code will surprise anyone, but:

public void onTodayClicked(View target) { // calculate the indexOf. It works and is not related to the question if (indexOf >= 0) { ListView list = (ListView) findViewById(R.id.events_list_view); list.setSelection(indexOf); } } 

I'm not sure that defining a layout is important to answer a question, but if you think so, I can add it too.

+4
source share
1 answer

You can achieve this in two ways:

Using the smoothScroll method is better, because it actually makes the transition smoothly - which means that it really scrolls to it. The only drawback is that it is only available after API level 11.

The setSelectionFromTop method works from API level 1, but instead of scrolling smoothly, it jumps to the line.

If you do not need to be located at the top of the screen, just to view the line, you can also use smoothScrollToPosition, which is an API level call.


If you give these methods a position that is on the FIRST list, they will work well. (From your description, I think you are probably calculating the last position, but I cannot be sure).

0
source

Source: https://habr.com/ru/post/1388468/


All Articles