简体   繁体   中英

How to make list view scrollable until the last element is on top of the screen

I am developing an application that needs to show calendar agenda, much like the agenda in the native calendar. I have a list view showing different events (Note: in the context of the question events is entity of my system). I want to provide a 'Today' button on this screen. When the user clicks on this button the events are supposed to be scrolled until the first event of the current's day schedule is on top of the screen. The problem occurs when I have only a few events scheduled from today on - so few that they do not fill a whole screen. Then the list view just scrolls until the last event in the calendar is on the bottom. This usually means that the desired effect of having the first today's event on top is not achieved.

Any suggestions how this can be done? I have thought of adding some blank elements at the end, but this seems ugly workaround, and furthermore it will require special device-specific calculations that will tell me how many elements to insert.

Edit :
Adding some code as requested in comment
Actually I am not sure 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 am not sure the layout definition is important to aid the answering of the question, but if you think so I can add it too.

You can achieve this by two ways:

  1. call smoothScrollToPositionFromTop method
  2. call setSelectionFromTop method

Using the smoothScroll method is better, because it actually does the transition smoothly - that means it really scrolls to it. The only downside is that it's only available after API level 11.

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

If you don't need to position to the top of the screen, only to view the row, you can also use smoothScrollToPosition, which is an API level 8 call.


If you give these methods the position, which is the FIRST in the list, they will work well. (From your description I think you probably calculate the last position, but I can't be sure).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM