我使用onfling一次滚动一个项目,只希望一个项目在页面上完全可见,而下一个项目部分可见。
我想知道,我怎样才能在RecyclerView中实现这一点。下面是适配器代码,它代替了cardview(如图所示),它是imageview:
public class SimpleItemRecyclerViewAdapter extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {
private final ArrayList<Movie> mValues;
public SimpleItemRecyclerViewAdapter(ArrayList<Movie> items) {
mValues = items;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.movie_list_content, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.mItem = mValues.get(position);
Context context = holder.imageView.getContext();
String logo = mValues.get(position).getPosterPath();
Picasso.with(context).load(logo).into(holder.imageView);
}
@Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public ImageView imageView;
public Movie mItem;
MainActivity mainActivity = new MainActivity();
public ViewHolder(View view) {
super(view);
mView = view;
imageView = (ImageView) view.findViewById(R.id.image_movie_poster);
android.view.ViewGroup.LayoutParams params = imageView.getLayoutParams();
params.height = (int) (mainActivity.height * 0.7);
imageView.setLayoutParams(params);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(view.getContext(), "Clicked", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public String toString() {
return "Blah";
}
}
}
最佳答案
这对我的水平回收车有用。您可以直接切换到垂直布局管理器。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
final SnapHelper snapHelper = new PagerSnapHelper();
snapHelper.attachToRecyclerView(recyclerView);
recyclerView.post(new Runnable() {
@Override
public void run() {
recyclerView.setAdapter(new TestAdapter());
}
});
}
private class TestAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
{
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int i) {
final View view =
LayoutInflater.from(parent.getContext())
.inflate(R.layout.test_card, parent, false);
int width = recyclerView.getWidth();
ViewGroup.LayoutParams params = view.getLayoutParams();
params.width = (int)(width * 0.8);
view.setLayoutParams(params);
return new TestViewHolder(view);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int i) {
TestViewHolder holder = (TestViewHolder) viewHolder;
holder.numText.setText(((Integer) i).toString());
}
@Override
public int getItemCount() {
return 20;
}
}