小编Rat*_*tty的帖子

确定项目是否在RecyclerView上可见

我已经构建了一个基本界面,其中包含一个CardView内部列表RecyclerView.添加卡后,我需要知道它是否在屏幕上可见.

我试图通过使用布局管理器的findLastVisibleItemPosition()方法获得这个,但它似乎返回一个项目少于预期的结果.例如,如果我有一张可见的卡片findLastVisibleItemPosition()返回-1(我希望看到可见卡片的索引0).

我简化的核心方法如下:

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 …
Run Code Online (Sandbox Code Playgroud)

android android-recyclerview

6
推荐指数
1
解决办法
1万
查看次数

标签 统计

android ×1

android-recyclerview ×1