先来一张效果图
注: 本文 需要用到的几个 第三方的库
compile 'com.android.support:recyclerview-v7:25.1.1' compile 'com.github.xxl6097:okhttputils:2.4.1' compile 'com.alibaba:fastjson:1.2.24' compile 'com.squareup.picasso:picasso:2.3.2'
第一步:布局里写一个RecyclerView
<android.support.v7.widget.RecyclerView android:id="@+id/recycleView" android:layout_width="match_parent" android:layout_height="wrap_content"/>
第二步,在MainActivity中 实例化RecyclerView
recyclerView = (RecyclerView) findViewById(R.id.recycleView);
第三步,联网获取数据 在这里 使用的是okhttpUtils
/** * 联网请求所需的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";
/** * 联网获取数据 */ private void getData() { OkHttpUtils .get() .url(url) .build() .execute(new StringCallback() { @Override public void onError(Call call, Exception e) { Log.d("MainActivity", "联网失败" + e.getMessage()); } @Override public void onResponse(Call call, String s) { Log.d("MainActivity", "联网成功" + s); // 对获取的JSON数据进行解析 parserData(s); } }); }
/** * 解析数据 * * @param s 网络请求的JSON字符串 */ private void parserData(String s) { JSONObject jsonObject = parseObject(s); String data = jsonObject.getString("data"); JSONObject dataObj = parseObject(data); String coming = dataObj.getString("coming"); List<ComingBean> comingslist = parseArray(coming, ComingBean.class); //测试是否解析数据成功 String strTest = comingslist.get(0).cat; Log.e("TAG", strTest + "222"); // 解析成功 设置适配器 }
第五步 创建适配器 并传递数据
MyRecyclerAdapter adapter = new MyRecyclerAdapter(this, comingslist); // 设置RecycleView的布局管理器 GridLayoutManager layoutManager = new GridLayoutManager(this, 1); recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(adapter);适配器的实例化 对象
package com.aegis.testtopguide; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Picasso; import java.util.List; /** * Created by SFS on 2017/2/8. * Description : */ public class MyRecyclerAdapter extends RecyclerView.Adapter { private Context context; private List<ComingBean> comingslist; private final LayoutInflater inflater; public MyRecyclerAdapter(Context context, List<ComingBean> comingslist) { this.context = context; this.comingslist = comingslist; inflater = LayoutInflater.from(context); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new MyViewHolder(inflater.inflate(R.layout.data_item, null)); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { MyViewHolder myViewHolder = (MyViewHolder) holder; myViewHolder.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) { ComingBean comingBean = comingslist.get(position); mv_name.setText(comingBean.nm); mv_date.setText(comingBean.showInfo); mv_dec.setText(comingBean.scm); //注:当你发下图片无法打开是,做个字符串替换即可 String imagUrl =comingBean.img; String newImagUrl = imagUrl.replaceAll("w.h", "50.80"); //加载图片 Picasso .with(context) .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="1" 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>
第六步 开始做导航
首先我们来写一个类,它起标记的作用,来放每一个item的对应的悬浮栏的字符串
public class NameBean { public String name; }
自定义一个接口 用来方便外部调用
/** * Created by SFS on 2017/2/8. * Description : 定义一个借口方便外界的调用 */ public interface DecorationCallback { String getGroupId(int position); String getGroupFirstLine(int position); }
package com.aegis.testtopguide; import android.content.Context; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.support.v7.widget.RecyclerView; import android.text.TextPaint; import android.text.TextUtils; import android.util.Log; import android.view.View; import java.util.List; import static android.content.ContentValues.TAG; /** * Created by on 2017/2/8. * Description : */ public class SectionDecoration extends RecyclerView.ItemDecoration { private List<NameBean> dataList; private DecorationCallback decorationCallback; private Paint paint; private TextPaint textPaint; private Paint.FontMetrics fontMetrics; private int topGap; private int alignBottom; public SectionDecoration(List<NameBean> dataList, Context context, DecorationCallback decorationCallback){ this.dataList = dataList; this.decorationCallback = decorationCallback; Resources res = context.getResources(); //设置悬浮栏的画笔---paint paint = new Paint(); paint.setColor(res.getColor(R.color.colorGray)); //设置悬浮栏中文本的画笔 textPaint = new TextPaint(); textPaint.setAntiAlias(true); textPaint.setTextSize(DensityUtil.dip2px(context, 14)); 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 = decorationCallback.getGroupId(pos); if (groupId.equals("-1")) return; //只有是同一组的第一个才显示悬浮栏 if (pos == 0 || isFirstInGroup(pos)) { outRect.top = topGap; if (dataList.get(pos).name == "") { outRect.top = 0; } } else { outRect.top = 0; } } @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 = 0; i < childCount; i++) { View view = parent.getChildAt(i); int position = parent.getChildAdapterPosition(view); String groupId = decorationCallback.getGroupId(position); if (groupId.equals("-1")) return; String textLine = decorationCallback.getGroupFirstLine(position).toUpperCase(); if (textLine == "") { float top = view.getTop(); float bottom = view.getTop(); c.drawRect(left, top, right, bottom, paint); return; } else { if (position == 0 || 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 = 0; i < childCount; i++) { View view = parent.getChildAt(i); int position = parent.getChildAdapterPosition(view); preGroupId = groupId; groupId = decorationCallback.getGroupId(position); if (groupId.equals("-1") || groupId.equals(preGroupId)) continue; String textLine = decorationCallback.getGroupFirstLine(position).toUpperCase(); if (TextUtils.isEmpty(textLine)) continue; int viewBottom = view.getBottom(); float textY = Math.max(topGap, view.getTop()); //下一个和当前不一样移动当前 if (position + 1 < itemCount) { //在 position后面+1 可以进行每一个条目都进行一次滑动 String nextGroupId = decorationCallback.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 + 2 * alignBottom, textY - alignBottom, textPaint); } } /** * 判断是不是第一个位置 * @param pos * @return */ private boolean isFirstInGroup(int pos) { if (pos == 0) { return true; } else { // 因为是根据 字符串内容的相同与否 来判断是不是同意组的,所以此处的标记id 要是String类型 // 如果你只是做联系人列表,悬浮框里显示的只是一个字母,则标记id直接用 int 类型就行了 String prevGroupId = decorationCallback.getGroupId(pos - 1); String groupId = decorationCallback.getGroupId(pos); //判断前一个字符串 与 当前字符串 是否相同 if (prevGroupId.equals(groupId)) { return false; } else { return true; } } } }第八步 在向list集合中先把每一个item的 起“标记”作用的字符串都加进去
/** * 在向list集合中先把每一个item的 起“标记”作用的字符串都加进去 * * @param comingslist */ private void setPullAction(List<ComingBean> comingslist) { dataList = new ArrayList<>(); for (int i = 0; i < comingslist.size(); i++) { NameBean nameBean = new NameBean(); String name0 = comingslist.get(i).comingTitle; nameBean.name = name0; dataList.add(nameBean); } }第九步 在setAdapter() 前,为RecyclerView添加ItemDecoration:(完整代码)
// 解析成功 设置适配器 setPullAction(comingslist); MyRecyclerAdapter adapter = new MyRecyclerAdapter(this, comingslist); // 设置RecycleView的布局管理器 GridLayoutManager layoutManager = new GridLayoutManager(this, 1); recyclerView.setLayoutManager(layoutManager); //为RecyclerView添加ItemDecoration: recyclerView.addItemDecoration(new SectionDecoration(dataList, mContext, new DecorationCallback() { @Override public String getGroupId(int position) { if (dataList.get(position).name != null) { return dataList.get(position).name; } return "-1"; } @Override public String getGroupFirstLine(int position) { if (dataList.get(position).name != null) { return dataList.get(position).name; } return ""; } })); recyclerView.setAdapter(adapter);
以上为功能模块的代码:
Demo 地址 https://github.com/shenshao520/TestTopGuide