Android 實(shí)現(xiàn)當(dāng)下最流行的吸頂效果
開(kāi)始逐漸領(lǐng)略到ItemDecoration的美~
今天讓我 使用 ItemDecoration 來(lái)完成 可推動(dòng)的懸浮導(dǎo)航欄的效果,最終實(shí)現(xiàn)的效果如下圖:

具體實(shí)現(xiàn)步驟如下:
根據(jù)我前面的文章所講的RecyclerView的基本使用,我們先來(lái)完成基本的recyclerView:
第一步:布局里寫一個(gè)RecyclerView
第二步:實(shí)例化
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
第三步:獲取所需的數(shù)據(jù) (這里我們來(lái)個(gè)真實(shí)點(diǎn)的情景,去聯(lián)網(wǎng)請(qǐng)求數(shù)據(jù))
//聯(lián)網(wǎng)獲取數(shù)據(jù) getDataFromNet();
/**
* 使用okhttpUtils進(jìn)行聯(lián)網(wǎng)請(qǐng)求數(shù)據(jù)
*/
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", "聯(lián)網(wǎng)失敗" + e.getMessage());
}
@Override
public void onResponse(String response, int id) {
Log.e("TAG", "聯(lián)網(wǎng)成功==" + response);
//聯(lián)網(wǎng)成功后使用fastjson解析
processData(response);
}
});
}
/**
* 使用fastjson進(jìn)行解析
*
* @param json
*/
private void processData(String json) {
//這里使用GsonFormat生成對(duì)應(yīng)的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);
//測(cè)試是否解析數(shù)據(jù)成功
// String strTest = comingslist.get(0).getCat();
// Log.e("TAG", strTest + "222");
//解析數(shù)據(jù)成功,設(shè)置適配器-->
}
}
第四步:解析數(shù)據(jù)成功后,創(chuàng)建并設(shè)置適配器,并傳遞相關(guān)數(shù)據(jù)
//解析數(shù)據(jù)成功,設(shè)置適配器 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);
//注:當(dāng)你發(fā)下圖片無(wú)法打開(kāi)是,做個(gè)字符串替換即可
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="1" android:orientation="vertical"> <TextView android:id="@+id/mv_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="神奇動(dòng)物在哪裏" 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=" | 專業(yè)" 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="神奇動(dòng)物城,法師顯超能" 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場(chǎng)" android:textColor="#99000000" android:textSize="11sp" /> </LinearLayout> </LinearLayout>
第五步:一定不能忘!?。?/strong>
recycleView不僅要設(shè)置適配器還要設(shè)置布局管理者,否則圖片不顯示
GridLayoutManager manager = new GridLayoutManager(this, 1); recyclerView.setLayoutManager(manager);
此時(shí)RecyclerView簡(jiǎn)單的完成效果如下:

下面開(kāi)始做 可推動(dòng)的 懸浮導(dǎo)航欄:
第一步:首先我們來(lái)寫一個(gè)類,它起標(biāo)記的作用,來(lái)放每一個(gè)item的對(duì)應(yīng)的懸浮欄的字符串
public class NameBean {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
第二步:自定義一個(gè)SectionDecoration 類 繼承 RecyclerView的ItemDecoration
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;
//設(shè)置懸浮欄的畫筆---paint
paint = new Paint();
paint.setColor(res.getColor(R.color.colorGray));
//設(shè)置懸浮欄中文本的畫筆
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 = callback.getGroupId(pos);
if (groupId.equals("-1")) return;
//只有是同一組的第一個(gè)才顯示懸浮欄
if (pos == 0 || isFirstInGroup(pos)) {
outRect.top = topGap;
if (dataList.get(pos).getName() == "") {
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 = 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 == 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 = 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());
//下一個(gè)和當(dāng)前不一樣移動(dòng)當(dāng)前
if (position + 1 < itemCount) {
String nextGroupId = callback.getGroupId(position + 1);
//組內(nèi)最后一個(gè)view進(jìn)入了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);
}
}
/**
* 判斷是不是組中的第一個(gè)位置
*
* @param pos
* @return
*/
private boolean isFirstInGroup(int pos) {
if (pos == 0) {
return true;
} else {
// 因?yàn)槭歉鶕?jù) 字符串內(nèi)容的相同與否 來(lái)判斷是不是同意組的,所以此處的標(biāo)記id 要是String類型
// 如果你只是做聯(lián)系人列表,懸浮框里顯示的只是一個(gè)字母,則標(biāo)記id直接用 int 類型就行了
String prevGroupId = callback.getGroupId(pos - 1);
String groupId = callback.getGroupId(pos);
//判斷前一個(gè)字符串 與 當(dāng)前字符串 是否相同
if (prevGroupId.equals(groupId)) {
return false;
} else {
return true;
}
}
}
//定義一個(gè)借口方便外界的調(diào)用
interface DecorationCallback {
String getGroupId(int position);
String getGroupFirstLine(int position);
}
}
第三步:在向list集合中先把每一個(gè)item的 起“標(biāo)記”作用的字符串都加進(jìn)去
setPullAction(comingslist);
private void setPullAction(List<WaitMVBean.DataBean.ComingBean> comingslist) {
dataList = new ArrayList<>();
for (int i = 0; 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() {
//返回標(biāo)記id (即每一項(xiàng)對(duì)應(yīng)的標(biāo)志性的字符串)
@Override
public String getGroupId(int position) {
if(dataList.get(position).getName()!=null) {
return dataList.get(position).getName();
}
return "-1";
}
//獲取同組中的第一個(gè)內(nèi)容
@Override
public String getGroupFirstLine(int position) {
if(dataList.get(position).getName()!=null) {
return dataList.get(position).getName();
}
return "";
}
}));
這樣就完成了~
再看一眼最終效果感受一下:

以上就是本文的全部?jī)?nèi)容,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助,同時(shí)也希望多多支持腳本之家!
相關(guān)文章
Android實(shí)現(xiàn)按鈕點(diǎn)擊事件的三種方法總結(jié)
Button是程序用于和用戶進(jìn)行交互的一個(gè)重要控件。既然有Button,那肯定有onClick方法,下面就教大家三種實(shí)現(xiàn)點(diǎn)擊事件的方法,感興趣的可以了解一下2022-04-04
詳解Android 7.0 Settings 加載選項(xiàng)
本篇文章主要介紹了Android 7.0 Settings 加載選項(xiàng),Android 7.0 Settings頂部多了一個(gè)建議選項(xiàng),多了個(gè)側(cè)邊欄,操作更加便捷了,有興趣的可以了解一下。2017-02-02
Android Messenger實(shí)現(xiàn)進(jìn)程間雙向通信
這篇文章主要為大家詳細(xì)介紹了Messenger實(shí)現(xiàn)進(jìn)程間雙向通信,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-05-05
Android 2d游戲開(kāi)發(fā)之貪吃蛇基于surfaceview
這篇文章主要介紹了Android 2d游戲開(kāi)發(fā)基于surfaceview的貪吃蛇,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-09-09
Android提高之SurfaceView的基本用法實(shí)例分析
這篇文章主要介紹了Android提高之SurfaceView的基本用法,非常實(shí)用的功能,需要的朋友可以參考下2014-08-08
Android自定義view實(shí)現(xiàn)進(jìn)度條指示效果
這篇文章主要為大家詳細(xì)介紹了Android自定義view實(shí)現(xiàn)進(jìn)度條指示效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-01-01
Android SharedPreferences實(shí)現(xiàn)記住密碼和自動(dòng)登錄界面
本篇文章主要介紹了Android記住密碼和自動(dòng)登錄界面的實(shí)現(xiàn)(SharedPreferences),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。2017-02-02

