I built a basic interface consisting of a CardView list inside a RecyclerView. When a map is added, I need to know if it is visible on the screen or not.
I am trying to trick this using the layoutListVisibleItemPosition () method, but it seems to return the result one element less than expected. For example, if I have 1 map that is visible findLastVisibleItemPosition () returns -1 (where I expect the index of the visible map to be 0).
My simplified core methods are as follows:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
items = new ArrayList<>();
RecyclerView recycList = (RecyclerView) findViewById(R.id.rv);
recycList.setHasFixedSize(true);
llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
recycList.setLayoutManager(llm);
recycList.addOnChildAttachStateChangeListener(new ChildAttachListener(llm));
adapter = new RecycAdapter(items);
recycList.setAdapter(adapter);
}
private void addItem(){
items.add(new Item());
adapter.notifyDataSetChanged();
}
private class ChildAttachListener implements OnChildAttachStateChangeListener{
LinearLayoutManager llm;
public ChildAttachListener(LinearLayoutManager llm){
super();
this.llm = llm;
}
@Override
public void onChildViewAttachedToWindow(View view) {
System.out.println("Items size = "+items.size() + ", Last Visible Item = "+llm.findLastVisibleItemPosition());
}
@Override
public void onChildViewDetachedFromWindow(View view) {
}
}
Return on adding the first item:
Items size = 1, Last Visible Item = -1
Return on adding the second item:
Items size = 2, Last Visible Item = 0
Items size = 2, Last Visible Item = 0
Return on adding the third item:
Items size = 3, Last Visible Item = 0
Items size = 3, Last Visible Item = 1
Items size = 3, Last Visible Item = 1
In all cases, all elements are visible (7 visible elements can be displayed on the screen).
- findLastVisibleItemPosition() , , ?
EDIT:
, - , , ( addItem()). addItem() .