滚动时更新recyclelerview的位置(android)

时间:2017-04-20 04:13:16

标签: android android-recyclerview

如何更新滚动位置。现在,每次点击项目时,位置都会更新。我想每次滚动时更新位置。我想做的是有一个文本视图,在滚动项目时会更新。

recyclerView.addOnItemTouchListener(new GalleryAdapter.RecyclerTouchListener(this, recyclerView, new GalleryAdapter.ClickListener()
            {

                @Override
                public void onClick(View view, int position) {

                    Intent intent = new Intent(mainActivityCarasoul.this, PDFViewerActivity.class);
                    intent.putExtra(PDFViewerActivity.TAG, books.get(position));
                    intent.putExtra("from", "mainActivityCarasoul");
                    startActivity(intent);
                }
                @Override
                public void onLongClick(View view, int position) {
                }
            }));

            recyclerView.addOnScrollListener(new CenterScrollListener());

            recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged(recyclerView, newState);
                   // title.setText(books.get(position).getName());

                }
            });

2 个答案:

答案 0 :(得分:0)

您好,您可以使用以下代码,

 mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener()
    {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy)
        {
            GridLayoutManager layoutManager = ((GridLayoutManager)mRecyclerView.getLayoutManager());
            int firstVisiblePosition = layoutManager.findFirstVisibleItemPosition();
            int findFirstCompletelyVisibleItemPosition = layoutManager.findFirstCompletelyVisibleItemPosition();
            int findLastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
            int findLastCompletelyVisibleItemPosition = layoutManager.findLastCompletelyVisibleItemPosition();
        }
    });

答案 1 :(得分:0)

使用它,你必须在你的活动和你的适配器类中维护一个selectedItem作为int intialize previousPoistion = -1;和selectedPosition = 1;

 @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            switch (newState) {
                case 0:
                    int pos = linearLayoutManager1.findLastVisibleItemPosition();
                    yourAdapter.selectedPosition = pos - 1;
                    previousPosition = pos - 1;
                    yourTextView.setText(yourLIst.get(pos-1));
                    break;
            }
        }
    });

并在适配器的onBindView Holder中

@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
if (position == selectedPosition) {
             //do what you want when selected
            } 
}