如何使用卡片更改水平回收 View 上第一个完整可见项目的边距(底部 20 dp)?我只能获取第一个完整可见项目的索引,但无法获取对 View 的任何引用。
mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
firstVisibleItem = lm.findFirstCompletelyVisibleItemPosition();
View view= mRecyclerView.getChildAt(firstVisibleItem);
RelativeLayout.LayoutParams lp= new RelativeLayout.LayoutParams(300, 150);
lp.setMargins(0, 0, 0, 20);
view.setLayoutParams(lp);
}
});
最佳答案
假设 view
包含对要更改边距的 View 的引用,您可以使用以下命令将底部边距设置为 20 像素:
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(0, 0, 0, 20);
view.setLayoutParams(lp);
请注意,这会将底部边距更改为 20 像素,而不是 20dp。您需要将 20dp 值转换为像素。 Converting pixels to dp将是了解如何完成转换的好地方。
您可能还需要更改 LinearLayout.LayoutParams 构造函数的高度和宽度参数以满足您的需要。
如果问题是获取对 View 的引用,发布一些代码会有所帮助。
编辑/更新 该代码有帮助。我认为您没有设置对所需 View 的访问权限。这是另一种方法:
mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
// Find the adapter position of the first fully visible item
// May return RecyclerView.NO_POSITION that is not handled here.
firstVisibleItem = lm.findFirstCompletelyVisibleItemPosition();
// Find the corresponding view holder for this position.
// MyViewHolder should already be defined (just don't know the name).
MyViewHolder vh = (MyViewHolder) mRecyclerView
.findViewHolderForAdapterPosition(firstVisibleItem);
// Get the layout parameters from the top-level item of this view.
// This could also be another view captured within the view holder.
RecyclerView.LayoutParams lp = (RecyclerView.LayoutParams) vh.itemView.getLayoutParams();
// Make our changes and set them.
lp.setMargins(0, 0, 0, 50);
vh.itemView.setLayoutParams(lp);
}
});
关于android - 更改 recyclerview 中第一个可见项目的边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37081076/