同时在RecyclerView中滚动多个项目,如轮播

时间:2017-06-09 17:51:46

标签: android android-recyclerview android-viewpager carousel

我想像轮播一样使用RecyclerView在屏幕上同时显示3个项目。

首先,在屏幕上显示项目#1#2和#3。 当我刷RecyclerView(像ViewPager)时,我想显示#4#5 et#6这样的项目:

  • 第一个屏幕

enter image description here

  • 滚动后的屏幕

enter image description here

如何实现此工作流程?谢谢你的帮助!

这是我的活动

public class CarouselActivity extends BaseActivity {

private RecyclerView recyclerView;

@Override
protected int getLayoutResourceId() {
    return R.layout.carousel_activity;
}

@Override
protected void setupViews()
{
    recyclerView = (RecyclerView)findViewById(R.id.recyclerview);
}


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ArrayList<CarouselItem> items = new ArrayList<>();

    items.add(new CarouselItem());
    items.add(new CarouselItem());
    items.add(new CarouselItem());
    items.add(new CarouselItem());
    items.add(new CarouselItem());
    items.add(new CarouselItem());


    recyclerView.setLayoutManager(new LinearLayoutManager(context,LinearLayoutManager.HORIZONTAL,false));
    recyclerView.setHasFixedSize(true);
    recyclerView.setAdapter(new CarouselAdapter(context,activity,items));
}
}

我的适配器

public class CarouselAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

protected ArrayList<CarouselItem> listItems;

protected Context context;
protected Activity activity;
protected LayoutInflater inflater;

public CarouselAdapter(Context context,
                       Activity activity,
                       ArrayList<CarouselItem> listItems)
{
    this.context = context;
    this.activity = activity;
    this.inflater = LayoutInflater.from (context);
    this.listItems = listItems;
}

@Override
public int getItemCount()
{
    return listItems.size();
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
    View v = inflater.inflate(R.layout.carousel_item, parent, false);

    return new ItemHolder(v);
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position)
{
    ItemHolder itemHolder = (ItemHolder)holder;

    itemHolder.itemView.getLayoutParams().width = ScreenHelper.getScreenWidthRatio(activity,33);
    itemHolder.itemView.getLayoutParams().height = ScreenHelper.getScreenWidthRatio(activity,50);

    itemHolder.itemView.setBackgroundColor((position % 2 == 0 ) ? Color.RED : Color.BLUE);

    int page = position + 1;
    itemHolder.tvPage.setText("" + page);
}

protected static class ItemHolder extends RecyclerView.ViewHolder
{
    private TextView tvPage;

    public ItemHolder(View itemView)
    {
        super(itemView);

        tvPage = (TextView)itemView.findViewById(R.id.tv_page);
    }
}
}

0 个答案:

没有答案