前言
其实就是一个横向的RecyclerView,记录一下其他的几个点,整体比较简单
实现
Java代码如下:
/**
* 侧滑列表
*/
public class HomeSideSlipView extends LinearLayout {
/**
* 上下圆角样式的判断
*/
public static final int LIST_TYPE_BG = 1;
public static final int ACT_TYPE_BG = 2;
private LinearLayout ll_all;
private Context mContext;
private RecyclerView rv;
private int position;
private int xOffset;
public HomeSideSlipView(Context context) {
super(context);
initView(context);
}
public HomeSideSlipView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
initView(context);
}
private void initView(Context context) {
mContext = context;
View view = LayoutInflater.from(mContext)
.inflate(R.layout.home_side_slide_view,this,true);
ll_all = view.findViewById(R.id.ll_all);
rv = view.findViewById(R.id.rv);
}
public void setType(int type){
ll_all.setBackgroundResource(type == LIST_TYPE_BG ? R.drawable.shape_white_bg10 : R.drawable.shape_white_bottom_r10);
}
public void setData(List<HomeGoodsInfoBean> mList, int type){
rv.setLayoutManager(new LinearLayoutManager(mContext,LinearLayoutManager.HORIZONTAL,false));
HomeSideAdapter adapter = new HomeSideAdapter(mList,type);
rv.setAdapter(adapter);
}
/**
* 保持状态
*/
@Override
protected void onDetachedFromWindow() {
LinearLayoutManager manager = (LinearLayoutManager) rv.getLayoutManager();
if(manager!=null){
position = manager.findFirstVisibleItemPosition();
View view = manager.findViewByPosition(position);
if(view != null){
ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
xOffset = view.getLeft() - lp.leftMargin; //设置了margin则减去
}
}
super.onDetachedFromWindow();
}
/**
* 恢复状态
*/
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if(rv!=null){
LinearLayoutManager manager = (LinearLayoutManager) rv.getLayoutManager();
if(manager != null) manager.scrollToPositionWithOffset(position, xOffset);
}
}
}
假如这个侧滑列表是一个RecyclerView列表中的一个item时,需要注意onDetachedFromWindow()方法中保存侧滑列表的滑动位置,并在onAttachedToWindow()方法中恢复滑动位置。
网友评论