Hide custom search bar if all items in adapter are showing

后端 未结 4 706
Happy的楠姐
Happy的楠姐 2021-01-29 12:24

The problem I have is that listView.getLastVisiblePosition always returns -1 so I can\'t hide the searchView. I check this right after setting the

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-29 12:45

    You can refer to my answer here Strange problem with broadcast receiver in Android not exactly the same but you can get the idea why your code not working.

    To make it more clear, when you set the adapter to the ListView, nothing has been drawn yet and the method getLastVisiblePosition() can only return the correct value after the listview finish drawing all of it's visible children and know which one is the last visible one.

    So, the most appropriate approach I can suggest here is trigger a callback after the listView finished drawing and we get the correct value then.

    The ListView with listener after drawing:

    static class MyListView extends ListView {
            private OnDrawCompletedListener mOnDrawCompletedListener;
    
            public MyListView(Context context) {
                super(context);
            }
    
            @Override
            protected void onDraw(Canvas canvas) {
                super.onDraw(canvas);
                if (mOnDrawCompletedListener != null) {
                    mOnDrawCompletedListener.onDrawCompleted();
                }
            }
    
            public void setOnDrawCompletedListener(OnDrawCompletedListener listener) {
                mOnDrawCompletedListener = listener;
            }
    
            public static interface OnDrawCompletedListener {
                public void onDrawCompleted();
            }
        }
    

    The sample code for getting last visible position

    mListView.setAdapter(new EfficientAdapter(this));
    //Will get -1 here
    Log.e("Question-17953268",
            "getLastVisiblePosition  = "
                    + mListView.getLastVisiblePosition());
    
    mListView.setOnDrawCompletedListener(new OnDrawCompletedListener() {
    
        @Override
        public void onDrawCompleted() {
            //Will get correct value here
            Log.e("Question-17953268",
                    "getLastVisiblePosition  = "
                            + mListView.getLastVisiblePosition());
        }
    
    });
    

提交回复
热议问题