Scroll a particular ListView item into view

泄露秘密 提交于 2019-12-24 18:30:27

问题


In my application, I have a ListView. The data for each item in the list is an instance of the SomeItem class. The list has a custom ArrayAdapter which has a custom view to display various fields of each items and overrides the getView() method. Skeleton code for the initialization of the list view:

ListView listView = (ListView) foo.getViewById(R.id.listView);

ArrayAdapter<SomeItem> adapter = new ArrayAdapter<SomeItem>(activity, R.layout.listItemView, R.id.textView) {
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Code to build the view with multiple child views
    }
}

Now assume I have a SomeItem instance. Its associated view may or may not be in the portion of the ListView which is shown on screen. If it is not, how can I get the ListView to scroll this particular item into view?

The only somewhat related method I’ve found is ListView#requestChildRectangleOnScreen(), which requires me to provide a child view which I don’t have. I have the item for the adapter. So I’m still not sure how to piece this together. Any pointers?


回答1:


You can try the following:

  1. Calculate the position of the SomeItem item you want to make visible. You can do this by iterating over the list of SomeItems that you pass to the adapter.

  2. Use listView.getFirstVisiblePosition(), listView.getLastVisiblePosition() and the calculated position to check if the item is visible on the list.

  3. If the item is not visible, make listView scroll to it by calling listView.smoothScrollToPosition(calculatedPosition).



来源:https://stackoverflow.com/questions/46595361/scroll-a-particular-listview-item-into-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!