Android 最流行的吸顶效果的实现及代码
开始逐渐领略到ItemDecoration的美~
今天让我 使用 ItemDecoration 来完成 可推动的悬浮导航栏的效果,最终实现的效果如下图:

具体实现步骤如下:
根据我前面的文章所讲的RecyclerView的基本使用,我们先来完成基本的recyclerView:
第一步:布局里写一个RecyclerView
第二步:实例化
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
第三步:获取所需的数据 (这里我们来个真实点的情景,去联网请求数据)
/**
* 联网请求所需的url
*/
public String url="http://api.meituan.com/mmdb/movie/v2/list/rt/order/coming.json?ci=1&limit=12&token=&__vhost=api.maoyan.com&utm_campaign=AmovieBmovieCD-1&movieBundleVersion=6801&utm_source=xiaomi&utm_medium=android&utm_term=6.8.0&utm_content=868030022327462&net=255&dModel=MI%205&uuid=0894DE03C76F6045D55977B6D4E32B7F3C6AAB02F9CEA042987B380EC5687C43&lat=40.100673&lng=116.378619&__skck=6a375bce8c66a0dc293860dfa83833ef&__skts=1463704714271&__skua=7e01cf8dd30a179800a7a93979b430b2&__skno=1a0b4a9b-44ec-42fc-b110-ead68bcc2824&__skcy=sXcDKbGi20CGXQPPZvhCU3%2FkzdE%3D"; //联网获取数据
getDataFromNet(); /**
* 使用okhttpUtils进行联网请求数据
*/
private void getDataFromNet() {
OkHttpUtils.
get()
.url(url)
.build()
.execute(new StringCallback() {
@Override
public void onError(okhttp3.Call call, Exception e, int id) {
Log.e("TAG", "联网失败" + e.getMessage());
} @Override
public void onResponse(String response, int id) {
Log.e("TAG", "联网成功==" + response); //联网成功后使用fastjson解析
processData(response);
}
});
} /**
* 使用fastjson进行解析
*
* @param json
*/
private void processData(String json) {
//这里使用GsonFormat生成对应的bean类
JSONObject jsonObject = parseObject(json); String data = jsonObject.getString("data");
JSONObject dataObj = JSON.parseObject(data); String coming = dataObj.getString("coming");
List<WaitMVBean.DataBean.ComingBean> comingslist = parseArray(coming, WaitMVBean.DataBean.ComingBean.class); //测试是否解析数据成功
// String strTest = comingslist.get(0).getCat();
// Log.e("TAG", strTest + "222"); //解析数据成功,设置适配器--> } }
第四步:解析数据成功后,创建并设置适配器,并传递相关数据
//解析数据成功,设置适配器
MyRecyclerAdapter adapter = new MyRecyclerAdapter( mContext,comingslist);
recyclerView.setAdapter(adapter);
适配器:
public class MyRecyclerAdapter extends RecyclerView.Adapter {
private final List<WaitMVBean.DataBean.ComingBean> comingslist;
private final Context mContext;
private final LayoutInflater mLayoutInflater;
public MyRecyclerAdapter(Context mContext, List<WaitMVBean.DataBean.ComingBean> comingslist) {
this.mContext = mContext;
this.comingslist = comingslist;
mLayoutInflater = LayoutInflater.from(mContext);
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new MyViewHolder(mLayoutInflater.inflate(R.layout.date_item, null));
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
MyViewHolder myholder = (MyViewHolder) holder;
myholder.setData(position);
}
@Override
public int getItemCount() {
return comingslist.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
private TextView mv_name;
private TextView mv_dec;
private TextView mv_date;
private ImageView imageView;
public MyViewHolder(View itemView) {
super(itemView);
mv_name = (TextView) itemView.findViewById(R.id.mv_name);
mv_dec = (TextView) itemView.findViewById(R.id.mv_dec);
mv_date = (TextView) itemView.findViewById(R.id.mv_date);
imageView = (ImageView) itemView.findViewById(R.id.image);
}
public void setData(int position) {
WaitMVBean.DataBean.ComingBean coming = comingslist.get(position);
String name = coming.getNm();
mv_name.setText(name);
String date = coming.getShowInfo();
mv_date.setText(date);
String dec = coming.getScm();
mv_dec.setText(dec);
//注:当你发下图片无法打开是,做个字符串替换即可
String imagUrl = coming.getImg();
String newImagUrl = imagUrl.replaceAll("w.h", "50.80");
//使用Glide加载图片
Glide.with(mContext)
.load(newImagUrl)
.into(imageView);
}
}
}
item的布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#ffffff"
android:gravity="center_vertical"
android:orientation="horizontal"> <ImageView
android:id="@+id/image"
android:layout_width="70dp"
android:layout_height="110dp"
android:layout_marginBottom="5dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="8dp"
android:layout_marginTop="5dp" /> <LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="6dp"
android:layout_weight=""
android:orientation="vertical"> <TextView
android:id="@+id/mv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="神奇動物在哪裏"
android:textColor="#000000"
android:textSize="15sp" /> <LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"> <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="观众"
android:textColor="#55000000"
android:textSize="14sp" /> <TextView
android:id="@+id/tv_people"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="9.0 "
android:textColor="#FFCE42"
android:textSize="18sp" /> <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" | 专业"
android:textColor="#55000000"
android:textSize="14sp" /> <TextView
android:id="@+id/tv_professional"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="6.7"
android:textColor="#FFCE42"
android:textSize="18sp" />
</LinearLayout> <TextView
android:id="@+id/mv_dec"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="神奇動物城,法師顯超能"
android:textColor="#99000000"
android:textSize="11sp" /> <TextView
android:id="@+id/mv_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="今天165家影院放映2088场"
android:textColor="#99000000"
android:textSize="11sp" />
</LinearLayout> </LinearLayout>
第五步:一定不能忘!!!
recycleView不仅要设置适配器还要设置布局管理者,否则图片不显示
GridLayoutManager manager = new GridLayoutManager(this, );
recyclerView.setLayoutManager(manager);
此时RecyclerView简单的完成效果如下:

下面开始做 可推动的 悬浮导航栏:
第一步:首先我们来写一个类,它起标记的作用,来放每一个item的对应的悬浮栏的字符串
public class NameBean {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class SectionDecoration extends RecyclerView.ItemDecoration {
private static final String TAG = "SectionDecoration";
private List<NameBean> dataList;
private DecorationCallback callback;
private TextPaint textPaint;
private Paint paint;
private int topGap;
private int alignBottom;
private Paint.FontMetrics fontMetrics;
public SectionDecoration(List<NameBean> dataList, Context context, DecorationCallback decorationCallback) {
Resources res = context.getResources();
this.dataList = dataList;
this.callback = decorationCallback;
//设置悬浮栏的画笔---paint
paint = new Paint();
paint.setColor(res.getColor(R.color.colorGray));
//设置悬浮栏中文本的画笔
textPaint = new TextPaint();
textPaint.setAntiAlias(true);
textPaint.setTextSize(DensityUtil.dip2px(context, ));
textPaint.setColor(Color.DKGRAY);
textPaint.setTextAlign(Paint.Align.LEFT);
fontMetrics = new Paint.FontMetrics();
//决定悬浮栏的高度等
topGap = res.getDimensionPixelSize(R.dimen.sectioned_top);
//决定文本的显示位置等
alignBottom = res.getDimensionPixelSize(R.dimen.sectioned_alignBottom);
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
int pos = parent.getChildAdapterPosition(view);
Log.i(TAG, "getItemOffsets:" + pos);
String groupId = callback.getGroupId(pos);
if (groupId.equals("-1")) return;
//只有是同一组的第一个才显示悬浮栏
if (pos == || isFirstInGroup(pos)) {
outRect.top = topGap;
if (dataList.get(pos).getName() == "") {
outRect.top = ;
}
} else {
outRect.top = ;
}
}
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
super.onDraw(c, parent, state);
int left = parent.getPaddingLeft();
int right = parent.getWidth() - parent.getPaddingRight();
int childCount = parent.getChildCount();
for (int i = ; i < childCount; i++) {
View view = parent.getChildAt(i);
int position = parent.getChildAdapterPosition(view);
String groupId = callback.getGroupId(position);
if (groupId.equals("-1")) return;
String textLine = callback.getGroupFirstLine(position).toUpperCase();
if (textLine == "") {
float top = view.getTop();
float bottom = view.getTop();
c.drawRect(left, top, right, bottom, paint);
return;
} else {
if (position == || isFirstInGroup(position)) {
float top = view.getTop() - topGap;
float bottom = view.getTop();
//绘制悬浮栏
c.drawRect(left, top - topGap, right, bottom, paint);
//绘制文本
c.drawText(textLine, left, bottom, textPaint);
}
}
}
}
@Override
public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
super.onDrawOver(c, parent, state);
int itemCount = state.getItemCount();
int childCount = parent.getChildCount();
int left = parent.getPaddingLeft();
int right = parent.getWidth() - parent.getPaddingRight();
float lineHeight = textPaint.getTextSize() + fontMetrics.descent;
String preGroupId = "";
String groupId = "-1";
for (int i = ; i < childCount; i++) {
View view = parent.getChildAt(i);
int position = parent.getChildAdapterPosition(view);
preGroupId = groupId;
groupId = callback.getGroupId(position);
if (groupId.equals("-1") || groupId.equals(preGroupId)) continue;
String textLine = callback.getGroupFirstLine(position).toUpperCase();
if (TextUtils.isEmpty(textLine)) continue;
int viewBottom = view.getBottom();
float textY = Math.max(topGap, view.getTop());
//下一个和当前不一样移动当前
if (position + < itemCount) {
String nextGroupId = callback.getGroupId(position + );
//组内最后一个view进入了header
if (nextGroupId != groupId && viewBottom < textY) {
textY = viewBottom;
}
}
//textY - topGap决定了悬浮栏绘制的高度和位置
c.drawRect(left, textY - topGap, right, textY, paint);
//left+2*alignBottom 决定了文本往左偏移的多少(加-->向左移)
//textY-alignBottom 决定了文本往右偏移的多少 (减-->向上移)
c.drawText(textLine, left + * alignBottom, textY - alignBottom, textPaint);
}
}
/**
* 判断是不是组中的第一个位置
*
* @param pos
* @return
*/
private boolean isFirstInGroup(int pos) {
if (pos == ) {
return true;
} else {
// 因为是根据 字符串内容的相同与否 来判断是不是同意组的,所以此处的标记id 要是String类型
// 如果你只是做联系人列表,悬浮框里显示的只是一个字母,则标记id直接用 int 类型就行了
String prevGroupId = callback.getGroupId(pos - );
String groupId = callback.getGroupId(pos);
//判断前一个字符串 与 当前字符串 是否相同
if (prevGroupId.equals(groupId)) {
return false;
} else {
return true;
}
}
}
//定义一个借口方便外界的调用
interface DecorationCallback {
String getGroupId(int position);
String getGroupFirstLine(int position);
}
}
第三步:在向list集合中先把每一个item的 起“标记”作用的字符串都加进去
setPullAction(comingslist);
private void setPullAction(List<WaitMVBean.DataBean.ComingBean> comingslist) {
dataList = new ArrayList<>();
for (int i = ; i < comingslist.size(); i++) {
NameBean nameBean = new NameBean();
String name0 = comingslist.get(i).getComingTitle();
nameBean.setName(name0);
dataList.add(nameBean);
}
}
第四步:在setAdapter() 前,为RecyclerView添加ItemDecoration:
recyclerView.addItemDecoration(new SectionDecoration(dataList,mContext, new SectionDecoration.DecorationCallback() {
//返回标记id (即每一项对应的标志性的字符串)
@Override
public String getGroupId(int position) {
if(dataList.get(position).getName()!=null) {
return dataList.get(position).getName();
}
return "-1";
}
//获取同组中的第一个内容
@Override
public String getGroupFirstLine(int position) {
if(dataList.get(position).getName()!=null) {
return dataList.get(position).getName();
}
return "";
}
}));
这样就完成了~
再看一眼最终效果感受一下:

Android 最流行的吸顶效果的实现及代码的更多相关文章
- React-Native解决ListView 在Android手机上无吸顶效果
stickySectionHeadersEnabled={true} stickyHeaderIndices={[0]}
- 自定义tab吸顶效果一(原理)
PS:问题:什么是吸顶,吸顶有什么作用,吸顶怎么使用? 在很多app商城中,介绍软件的时候就会使用吸顶效果, 吸顶有很多作用,一个最简单粗暴的作用就是,让用户知道此刻在浏览哪个模块,并可以选择另外的模 ...
- tabControl组件的吸顶效果
最开始,还没有使用better-scroll插件的时候,直接在class中设定了一定的position为sticky,设置一定的top达成了效果.但是,使用better-scroll组件后,这些属性就 ...
- Html吸顶效果
Html吸顶效果 一.HTML HTML中需要给div一个id <!DOCTYPE html> <html lang="en"> <head> ...
- 基于scroll的吸顶效果
本次要实现的是一种常见的网页效果,如下: 页面由头部,导航,主体内容三部分组成,当页面发生滚动时,头部逐渐隐藏,导航部分向上移动,直到导航部分距离浏览器顶部为零时,导航部分固定不动,保持吸顶效果,如下 ...
- better-scroll之吸顶效果巨坑挣扎中
今天和大家分享下better-scroll这款移动端用来解决各种滚动需求的插件(目前已经支持PC) 关于其中的API大家可以去官网看下 这里就给大家介绍几种常用的以及需要注意的点是什么 首先说一下b ...
- js之吸顶效果
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- react.js中实现tab吸顶效果问题
在react项目开发中有一个需求是,页面滚动到tab所在位置时,tab要固定在顶部. 实现的思路其实很简单,就是判断当滚动距离scrollTop大于tab距离页面顶部距离offsetTop时,将tab ...
- [RN] React Native 头部 滑动吸顶效果的实现
React Native 头部 滑动吸顶效果的实现 效果如下图所示: 实现方法: 一.吸顶组件封装 StickyHeader .js import * as React from 'react'; i ...
随机推荐
- [P2996][USACO10NOV]拜访奶牛Visiting Cows (树形DP)
之前写在洛谷,结果没保存,作废…… 听说考前写题解RP++哦 思路 很容易想到是 树形DP 如果树形DP不知道是什么的话推荐百度一下 我在这里用vector储存边 设状态f[i][0]为i点不访问,f ...
- python网络编程(一)
socket简介 1.本地的进程间通信(IPC)有很多种方式,例如 队列 同步(互斥锁.条件变量等) 以上通信方式都是在一台机器上不同进程之间的通信方式,那么问题来了 网络中进程之间如何通信? 2. ...
- java第二周的学习知识
1.java基本运行单位是类,类的组成成员为成员变量和方法.成员变量的种类有public,default(就是不写),protected,private.public:public可以修饰类,数据成员 ...
- ISDN简记
简介 ISDN:(Integrated Services Digital Network,综合业务数字网) 是以综合数字电话网(IDN)为基础发展演变而形成的通信网,能够提供端到端的数字连接,用来支持 ...
- 【分块】教主的魔法 @洛谷P2801/upcexam3138
时间限制: 1 Sec 内存限制: 128 MB 题目描述 教主最近学会了一种神奇的魔法,能够使人长高.于是他准备演示给XMYZ信息组每个英雄看.于是N个英雄们又一次聚集在了一起,这次他们排成了一列, ...
- 【小y设计】二维码条形码打印编辑器
条码打印,价格标签打印,需要对打印进行排版,于是设计了一个简单的编辑器 支持条码二维码打印进行编辑排版,支持文字.图片.条码.二维码.直线,能自由拖拉,删除,并可保存为模版. 界面如下 (下载Demo ...
- SpringMVC的拦截器(Interceptor)和过滤器(Filter)的区别与联系
摘自: http://blog.csdn.net/xiaoyaotan_111/article/details/53817918 一 简介 (1)过滤器: 依赖于servlet容器.在实现上基于函数回 ...
- MFC更换窗口图标
https://blog.csdn.net/deep_kang/article/details/72722692: MFC更换图标,图像默认为MFC,主要步骤有三步. 第一步 找到一张图片(坑点: ...
- 资源贴——以备时时查询用
目录区 AI教程 AI教程 1.AI教程!教你绘制小清新巴士 2.AI教程!如何使用基础图形来绘制消防插画 3.AI教程!教你绘制秋日插画 4.AI教程!教你制作色彩分明的街边场景插画 ...
- [Canvas]空战游戏 已经可以玩了 1.13Playable
空战游戏做到这里,己方运动,己方发射子弹,敌方运动,敌方发射子弹,子弹与飞机碰撞,飞机与飞机碰撞都已经具备了,换言之已经可以玩了. 还需要一个奖励升级系统,在上面显示击落敌机数量等,还有己方不幸被击落 ...