How/where in the code to detect wether in ListFragment's ListView all items are visible?

拟墨画扇 提交于 2020-02-06 06:56:41

问题


I am trying to change the ActionBar's action depending on wether all list items are visible (there's less items that fit to the screen => show "Add item" action | there are some items invisible => show "Search" action)

What method of ListFragment should I override in order to be able to use getListView().getLastVisiblePosition() and get not -1?

This is the code from my ListFragment, but in onCreateOptionsMenu lv.getLastVisiblePosition() always returns -1.

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.list, menu);

    final MenuItem search = menu.findItem(R.id.menu_item_search);
    final MenuItem add = menu.findItem(R.id.menu_item_add_item);

    final ListView lv = getListView();
    if (lv.getFirstVisiblePosition() == 0 && lv.getLastVisiblePosition() == mAdapter.getCount()-1) {
        // all items visible: show add, hide search
        search.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
    } else {
        // not all items visible: show search, hide add
        add.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
    }
    // ...
}

回答1:


getLastVisiblePosition returns valid position only when adapter's items were added and layed out by a hosing ListView, i don't know any method of asking a ListView when it happens, so the best option would be just to listen when the UI thread goes to block waiting for more messages:

Looper.myQueue().addIdleHandler

and call getLastVisiblePosition() inside IdleHandler#queueIdle()




回答2:


To get visible child count in ListView.

int visibleChildCount = (listView.getLastVisiblePosition() - listView.getFirstVisiblePosition()) + 1;

Now get total child count in ListView,

int totalChildCount = listView.getAdapter().getCount;

Hide / Show Actionbar Icon.

if(totalChildCount>visibleChildCount){
  // Visible
}else{
  // Gone
} 

Hope this will help you.



来源:https://stackoverflow.com/questions/36055179/how-where-in-the-code-to-detect-wether-in-listfragments-listview-all-items-are

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