腾讯微博列表展示的功能实现

资料和思维逻辑来源于网络学习——>黑马程序员

从大学起就一直有看黑马的一些视频,现在没事偶尔也会去看一下,
整体教学质量都是很不错的。

这次去看到他有这个例子,就借鉴他的资料,自己写了一个,主要是我把BaseAdapter换成github上开源的BaseRecyclerViewAdapterHelper,其他的地方没有太大的改动,加了刷新和加载更多

先看效果图

这里写图片描述

引入我们要使用的工具

 compile 'com.github.CymChad:BaseRecyclerViewAdapterHelper:2.9.30'
    compile 'com.android.support:recyclerview-v7:26.0.0-alpha1'
    compile 'com.google.code.gson:gson:2.2.4'

GlobalUtils包含获取assets资源,测量屏幕宽度等工具类

package tsou.cn.weibolist.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.text.format.DateFormat;
import android.util.DisplayMetrics;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;


public class GlobalUtils {

    private static Context context;

    private static int mScreenWidth;
    private static int mScreenHeight;
    private static float mDensity;

    public static void init(Context context) {
        GlobalUtils.context = context;

        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        mScreenWidth = dm.widthPixels;
        mScreenHeight = dm.heightPixels;
        mDensity = dm.density;
    }

    /**
     * 单位转换dp转px
     */
    public static int dp2px(int dp) {
        return (int) (dp * mDensity + 0.5f);
    }

    /**
     * 读取assets目录下的文件
     *
     * @param fileName 文件名
     * @return
     */
    public static String readAssets(String fileName) {
        String str = "";
        try {
            InputStream stream = context.getResources().getAssets().open(fileName);
            byte[] buffer = new byte[1024];
            int len = -1;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            while ((len = stream.read(buffer)) != -1) {
                // 读取数据到内存中
                baos.write(buffer, 0, len);
            }
            str = baos.toString("utf-8");
            stream.close();
            baos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

    public static String formatDate(long time) {
        return DateFormat.format("yyyy-MM-dd kk:mm:ss", time).toString();
    }

    /**
     * 根据图片名称获取资源id
     * 例如:传入"avatar_01", 表示获取整数值R.drawable.avatar_01
     *
     * @param context
     * @param drawableName
     * @return
     */
    public static int getResId(Context context, String drawableName) {
        return context.getResources().getIdentifier(
                drawableName, "drawable", context.getPackageName());
    }

    /**
     * 获取宫格图片的宽高
     */
    public static int getGridWidth() {
        // 左边距:   10dp
        // 右边距:   10dp
        // 图片宫格的宽度 = (屏幕宽度-左边距-右边距) / 3
        return (GlobalUtils.mScreenWidth - GlobalUtils.dp2px(10 + 10)) / 3;
    }

    /**
     * 根据一张原图生成一张指定宽高的图片
     *
     * @param bitmap 原图
     * @param width  要生成图片的宽高
     * @return
     */
    public static Bitmap createBitmap(Bitmap bitmap, int width) {
        float scaleX = ((float) width) / bitmap.getWidth();
        float scaleY = ((float) width) / bitmap.getHeight();
        Matrix matrix = new Matrix();
        matrix.postScale(scaleX, scaleY);
        return Bitmap.createBitmap(bitmap, 0, 0,
                bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }
}

初始化GlobalUtils类

package tsou.cn.weibolist;

import android.app.Application;

import tsou.cn.weibolist.util.GlobalUtils;

/**
 * Created by Administrator on 2017/11/13 0013.
 */

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        // 初始化GlobalUtils类
        GlobalUtils.init(this);
    }
}

主页列表布局

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="tsou.cn.weibolist.MainActivity">

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipe_refresh"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:layout_editor_absoluteX="8dp"
            tools:layout_editor_absoluteY="8dp" />
    </android.support.v4.widget.SwipeRefreshLayout>

</FrameLayout>

创建列表adapter

package tsou.cn.weibolist.adapter;

import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.List;

import tsou.cn.weibolist.R;
import tsou.cn.weibolist.bean.Weibo;
import tsou.cn.weibolist.util.EmojiUtil;
import tsou.cn.weibolist.util.GlobalUtils;
import tsou.cn.weibolist.util.LinkifyUtil;

/**
 * Created by Administrator on 2017/11/13 0013.
 */

public class WeiboAdapter extends BaseQuickAdapter<Weibo.WeiboBean, BaseViewHolder> {


    public WeiboAdapter(@Nullable List<Weibo.WeiboBean> data) {
        super(R.layout.item_weibo, data);
    }

    @Override
    protected void convert(BaseViewHolder helper, Weibo.WeiboBean item) {
        helper.setText(R.id.tv_user, item.getUsername());
        helper.setText(R.id.tv_user_introduction, item.getUser_introduction());
        // 显示头像
        int imageResId = GlobalUtils.getResId(helper.itemView.getContext(), item.getAvatar());
        helper.setBackgroundRes(R.id.iv_avatar, imageResId);
        // 微博内容
        //helper.setText(R.id.tv_content, item.getContent());
        EmojiUtil.setText((TextView) helper.getView(R.id.tv_content), item.getContent());
        LinkifyUtil.addCustomLink((TextView) helper.getView(R.id.tv_content));
        LinkifyUtil.addUserCustomLink((TextView) helper.getView(R.id.tv_content));


        helper.setText(R.id.tv_date, GlobalUtils.formatDate(item.getDate()));

        //展示九宫格
        GridLayoutManager manager = new GridLayoutManager(mContext, 3);
        RecyclerView mRecyclerView = helper.getView(R.id.rv_weibo_images);
        mRecyclerView.setLayoutManager(manager);
        ImageAdapter mAdapter = new ImageAdapter(null);
        mRecyclerView.setAdapter(mAdapter);

        //显示微博图片
        int imageCount = item.getImageUrls() == null ? 0 : item.getImageUrls().size();
        if (imageCount == 0) {//没有微博
            mRecyclerView.setVisibility(View.GONE);
        } else {//有微博
            mRecyclerView.setVisibility(View.VISIBLE);
            //刷新图片数据
            mAdapter.setNewData(item.getImageUrls());

            //动态指定图片宫格的宽高和recycleview的宽高
            //1张图片->1列
            //4张图片 ->2列
            //其他  ->3列
            ViewGroup.LayoutParams layoutParams = mRecyclerView.getLayoutParams();
            if (imageCount == 1) {
                manager.setSpanCount(1);
                layoutParams.width = ViewGroup.LayoutParams.WRAP_CONTENT;
            } else if (imageCount == 4) {
                manager.setSpanCount(2);
                //两个图片的宽度
                layoutParams.width = GlobalUtils.getGridWidth() * 2;
            } else {
                manager.setSpanCount(3);
                layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
            }

        }

    }

}

图片列表adapter

package tsou.cn.weibolist.adapter;

import android.support.annotation.Nullable;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.List;

import tsou.cn.weibolist.R;
import tsou.cn.weibolist.util.GlobalUtils;

/**
 * Created by Administrator on 2017/11/13 0013.
 */

public class ImageAdapter extends BaseQuickAdapter<String, BaseViewHolder> {


    public ImageAdapter(@Nullable List<String> data) {
        super(R.layout.item_image, data);
    }

    @Override
    protected void convert(BaseViewHolder helper, String item) {
        //动态设置图片宫格的宽高
        //1张图片 -> 宫格的宽高为图片的宽高
        //其他情况  -> 宫格的宽高为宽度3分之一
        ViewGroup.LayoutParams layoutParams = helper.itemView.getLayoutParams();
        int resId = GlobalUtils.getResId(mContext, item);
        if (getItemCount() == 1) {//一张图片
            layoutParams.width = GlobalUtils.getGridWidth() * 3;
            layoutParams.height = GlobalUtils.getGridWidth() * 3;

//            Bitmap bitmap = BitmapFactory.decodeResource(
//                    mContext.getResources(), resId);
//            // 指定宫格的宽高为图片的宽高
//            layoutParams.width = bitmap.getWidth();
//            layoutParams.height = bitmap.getHeight();

            helper.setBackgroundRes(R.id.iv_image, resId);
        } else {
            layoutParams.width = GlobalUtils.getGridWidth();
            layoutParams.height = GlobalUtils.getGridWidth();
            helper.setBackgroundRes(R.id.iv_image, resId);
        }


    }


}

显示文本和表情

package tsou.cn.weibolist.util;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.widget.TextView;

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import tsou.cn.weibolist.R;

/**
 * Created by Administrator on 2017/11/13 0013.
 */

public class EmojiUtil {

    /**
     * 显示文本和表情
     *
     * @param textView
     * @param text
     */
    public static void setText(TextView textView, String text) {
        Context context = textView.getContext();
        Resources resources = context.getResources();
        SpannableString ss = new SpannableString(text);

        // 正则表达式: [高兴]
        Pattern p = Pattern.compile("\\[([A-Za-z\u4E00-\u9FA5]+)\\]");
        Matcher matcher = p.matcher(ss);
        while (matcher.find()) {
            // 匹配到一个表情字符串
            String emoji = matcher.group();
            // 过滤非表情符,比如: [xxx]
            if (EMOJI_DATAS.containsKey(emoji)) {   // 是表情才处理
                // 指定了一张图片
                Bitmap bitmap = BitmapFactory.decodeResource(resources, EMOJI_DATAS.get(emoji));
                bitmap = GlobalUtils.createBitmap(bitmap, GlobalUtils.dp2px(20));     // 图片的宽高为20dp
                ImageSpan span = new ImageSpan(context, bitmap, ImageSpan.ALIGN_BOTTOM);
                int start = matcher.start();
                int end = matcher.end();
                ss.setSpan(span, start, end, 0);
            }
        }
        textView.setText(ss);
    }

    private static final HashMap<String, Integer> EMOJI_DATAS = new HashMap<String, Integer>();

    static {
        EMOJI_DATAS.put("[微笑]", R.drawable.smiley_0);
        EMOJI_DATAS.put("[伤心]", R.drawable.smiley_1);
        EMOJI_DATAS.put("[美女]", R.drawable.smiley_2);
        EMOJI_DATAS.put("[发呆]", R.drawable.smiley_3);
        EMOJI_DATAS.put("[墨镜]", R.drawable.smiley_4);
        EMOJI_DATAS.put("[大哭]", R.drawable.smiley_5);
        EMOJI_DATAS.put("[害羞]", R.drawable.smiley_6);
        EMOJI_DATAS.put("[闭嘴]", R.drawable.smiley_7);
        EMOJI_DATAS.put("[睡觉]", R.drawable.smiley_8);
        EMOJI_DATAS.put("[伤心]", R.drawable.smiley_9);

        EMOJI_DATAS.put("[冷汗]", R.drawable.smiley_10);
        EMOJI_DATAS.put("[发怒]", R.drawable.smiley_11);
        EMOJI_DATAS.put("[调皮]", R.drawable.smiley_12);
        EMOJI_DATAS.put("[呲牙]", R.drawable.smiley_13);
        EMOJI_DATAS.put("[惊讶]", R.drawable.smiley_14);
        EMOJI_DATAS.put("[难过]", R.drawable.smiley_15);
        EMOJI_DATAS.put("[酷]", R.drawable.smiley_16);
        EMOJI_DATAS.put("[汗]", R.drawable.smiley_17);
        EMOJI_DATAS.put("[抓狂]", R.drawable.smiley_18);
        EMOJI_DATAS.put("[吐]", R.drawable.smiley_19);

        EMOJI_DATAS.put("[偷笑]", R.drawable.smiley_20);
        EMOJI_DATAS.put("[快乐]", R.drawable.smiley_21);
        EMOJI_DATAS.put("[奇]", R.drawable.smiley_22);
        EMOJI_DATAS.put("[傲]", R.drawable.smiley_23);
        EMOJI_DATAS.put("[饿]", R.drawable.smiley_24);
        EMOJI_DATAS.put("[累]", R.drawable.smiley_25);
        EMOJI_DATAS.put("[惊恐]", R.drawable.smiley_26);
        EMOJI_DATAS.put("[汗]", R.drawable.smiley_27);
        EMOJI_DATAS.put("[高兴]", R.drawable.smiley_28);
        EMOJI_DATAS.put("[大兵]", R.drawable.smiley_29);

        EMOJI_DATAS.put("[奋斗]", R.drawable.smiley_30);
        EMOJI_DATAS.put("[骂]", R.drawable.smiley_31);
        EMOJI_DATAS.put("[疑问]", R.drawable.smiley_32);
        EMOJI_DATAS.put("[嘘]", R.drawable.smiley_33);
        EMOJI_DATAS.put("[晕]", R.drawable.smiley_34);
        EMOJI_DATAS.put("[痛苦]", R.drawable.smiley_35);
        EMOJI_DATAS.put("[衰]", R.drawable.smiley_36);
        EMOJI_DATAS.put("[鬼]", R.drawable.smiley_37);
        EMOJI_DATAS.put("[敲打]", R.drawable.smiley_38);
        EMOJI_DATAS.put("[再见]", R.drawable.smiley_39);

        EMOJI_DATAS.put("[冷汗]", R.drawable.smiley_40);
        EMOJI_DATAS.put("[挖鼻]", R.drawable.smiley_41);
        EMOJI_DATAS.put("[鼓掌]", R.drawable.smiley_42);
        EMOJI_DATAS.put("[出丑]", R.drawable.smiley_43);
        EMOJI_DATAS.put("[坏笑]", R.drawable.smiley_44);
        EMOJI_DATAS.put("[左嘘]", R.drawable.smiley_45);
        EMOJI_DATAS.put("[右嘘]", R.drawable.smiley_46);
        EMOJI_DATAS.put("[打哈欠]", R.drawable.smiley_47);
        EMOJI_DATAS.put("[鄙视]", R.drawable.smiley_48);
        EMOJI_DATAS.put("[委屈]", R.drawable.smiley_49);

        EMOJI_DATAS.put("[快哭了]", R.drawable.smiley_50);
        EMOJI_DATAS.put("[邪恶]", R.drawable.smiley_51);
        EMOJI_DATAS.put("[亲亲]", R.drawable.smiley_52);
        EMOJI_DATAS.put("[吓吓]", R.drawable.smiley_53);
        EMOJI_DATAS.put("[可怜]", R.drawable.smiley_54);
        EMOJI_DATAS.put("[菜刀]", R.drawable.smiley_55);
        EMOJI_DATAS.put("[西瓜]", R.drawable.smiley_56);
        EMOJI_DATAS.put("[啤酒]", R.drawable.smiley_57);
        EMOJI_DATAS.put("[篮球]", R.drawable.smiley_58);
        EMOJI_DATAS.put("[乒乓球]", R.drawable.smiley_59);

        EMOJI_DATAS.put("[喝茶]", R.drawable.smiley_60);
        EMOJI_DATAS.put("[吃饭]", R.drawable.smiley_61);
        EMOJI_DATAS.put("[猪头]", R.drawable.smiley_62);
        EMOJI_DATAS.put("[鲜花]", R.drawable.smiley_63);
        EMOJI_DATAS.put("[花谢]", R.drawable.smiley_64);
        EMOJI_DATAS.put("[吻]", R.drawable.smiley_65);
        EMOJI_DATAS.put("[红心]", R.drawable.smiley_66);
        EMOJI_DATAS.put("[心碎]", R.drawable.smiley_67);
        EMOJI_DATAS.put("[生日]", R.drawable.smiley_68);
        EMOJI_DATAS.put("[闪电]", R.drawable.smiley_69);

        EMOJI_DATAS.put("[地雷]", R.drawable.smiley_70);
        EMOJI_DATAS.put("[刀]", R.drawable.smiley_71);
        EMOJI_DATAS.put("[足球]", R.drawable.smiley_72);
        EMOJI_DATAS.put("[甲虫]", R.drawable.smiley_73);
        EMOJI_DATAS.put("[便便]", R.drawable.smiley_74);
        EMOJI_DATAS.put("[月亮]", R.drawable.smiley_75);
        EMOJI_DATAS.put("[太阳]", R.drawable.smiley_76);
        EMOJI_DATAS.put("[礼物]", R.drawable.smiley_77);
        EMOJI_DATAS.put("[拥抱]", R.drawable.smiley_78);
        EMOJI_DATAS.put("[强]", R.drawable.smiley_79);

        EMOJI_DATAS.put("[弱]", R.drawable.smiley_80);
        EMOJI_DATAS.put("[握手]", R.drawable.smiley_81);
        EMOJI_DATAS.put("[胜利]", R.drawable.smiley_82);
        EMOJI_DATAS.put("[抱拳]", R.drawable.smiley_83);
        EMOJI_DATAS.put("[勾引]", R.drawable.smiley_84);
        EMOJI_DATAS.put("[握拳]", R.drawable.smiley_85);
        EMOJI_DATAS.put("[差劲]", R.drawable.smiley_86);
        EMOJI_DATAS.put("[爱你]", R.drawable.smiley_87);
        EMOJI_DATAS.put("[No]", R.drawable.smiley_88);
        EMOJI_DATAS.put("[OK]", R.drawable.smiley_89);

        EMOJI_DATAS.put("[爱情]", R.drawable.smiley_90);
        EMOJI_DATAS.put("[飞吻]", R.drawable.smiley_91);
        EMOJI_DATAS.put("[跳跳]", R.drawable.smiley_92);
        EMOJI_DATAS.put("[发抖]", R.drawable.smiley_93);
        EMOJI_DATAS.put("[怄火]", R.drawable.smiley_94);
        EMOJI_DATAS.put("[转圈]", R.drawable.smiley_95);
        EMOJI_DATAS.put("[磕头]", R.drawable.smiley_96);
        EMOJI_DATAS.put("[回头]", R.drawable.smiley_97);
        EMOJI_DATAS.put("[跳绳]", R.drawable.smiley_98);
        EMOJI_DATAS.put("[投降]", R.drawable.smiley_99);

        EMOJI_DATAS.put("[激动]", R.drawable.smiley_100);
        EMOJI_DATAS.put("[乱舞]", R.drawable.smiley_101);
        EMOJI_DATAS.put("[献吻]", R.drawable.smiley_102);
        EMOJI_DATAS.put("[左太极]", R.drawable.smiley_103);
        EMOJI_DATAS.put("[右太极]", R.drawable.smiley_104);
    }
}

Linkify类自定义超链接

package tsou.cn.weibolist.util;

import android.text.util.Linkify;
import android.widget.TextView;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 自定义超链接
 *
 */
public class LinkifyUtil {

    /**
     * 添加自定义超链接
     */
    public static void addCustomLink(TextView textView) {
        Pattern pattern = Pattern.compile("\\@([A-Za-z0-9\u4E00-\u9FA5]+)\\.?");
        // http://www.baidu.com/path?uid=1&username=xx
        String scheme = "huangxiaoguo://user?id=";

        // 匹配过滤器
        Linkify.MatchFilter matchFilter = new Linkify.MatchFilter() {
            @Override
            public boolean acceptMatch(CharSequence s, int start, int end) {
                String text = s.subSequence(start, end).toString();
                if (text.endsWith(".")) { // 邮箱,不需要匹配
                    return false;
                } else {
                    return true;    // 返回true会显示为超链接
                }
            }
        };
        Linkify.TransformFilter transformFilter = null;
        Linkify.addLinks(textView, pattern, scheme, matchFilter, transformFilter);
    }

    public static void addUserCustomLink(TextView textView) {
        // @用户:
        Pattern pattern = Pattern.compile("\\#([A-Za-z0-9\u4E00-\u9FA5]+)\\#");
        // http://www.baidu.com/path?uid=1&username=xx
        String scheme = "huangxiaoguo://topic?id=";
        // 匹配过滤器
        Linkify.MatchFilter matchFilter = new Linkify.MatchFilter() {
            @Override
            public boolean acceptMatch(CharSequence s, int start, int end) {
                String text = s.subSequence(start, end).toString();
                return true;
            }
        };
        Linkify.TransformFilter transformFilter = new Linkify.TransformFilter() {
            @Override
            public String transformUrl(Matcher match, String url) {
                return match.group(1);
            }
        };
        Linkify.addLinks(textView, pattern, scheme, matchFilter, transformFilter);
    }
}

manifest配置点击用户链接时,要调起该Activity

 <!--点击用户链接时,要调起该Activity-->
        <activity android:name=".avtivity.UserActivity">
            <intent-filter>
                <action android:name="android.intent.action.VIEW"/>
                <category android:name="android.intent.category.DEFAULT"/>
                <data android:scheme="huangxiaoguo" android:host="user"/>
            </intent-filter>
        </activity>
        <activity android:name=".avtivity.TopicActivity">
            <intent-filter>
                <action android:name="android.intent.action.VIEW"/>
                <category android:name="android.intent.category.DEFAULT"/>
                <data android:scheme="huangxiaoguo" android:host="topic"/>
            </intent-filter>
        </activity>

主页逻辑

package tsou.cn.weibolist;

import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

import tsou.cn.weibolist.adapter.WeiboAdapter;
import tsou.cn.weibolist.bean.Weibo;
import tsou.cn.weibolist.util.GlobalUtils;
import tsou.cn.weibolist.view.CustomLoadMoreView;

public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener,
        BaseQuickAdapter.RequestLoadMoreListener {

    private RecyclerView mRecyclerView;
    private WeiboAdapter mAdapter;
    private SwipeRefreshLayout mSwipeRefresh;
    private int mLastIndex;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initRecyclerView();
        initListener();
        mAdapter.setEnableLoadMore(false);
        mSwipeRefresh.setRefreshing(true);
        fetchData(true);
    }

    private void initView() {
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        mSwipeRefresh = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
        mSwipeRefresh.setColorSchemeColors(Color.rgb(63, 81,
                181));
    }

    private void initRecyclerView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new WeiboAdapter(null);
        mAdapter.isFirstOnly(false);
        mAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mAdapter.setLoadMoreView(new CustomLoadMoreView());
        mRecyclerView.setAdapter(mAdapter);
    }

    private void initListener() {
        mSwipeRefresh.setOnRefreshListener(this);
        mAdapter.setOnLoadMoreListener(this, mRecyclerView);
    }

    private boolean mIsRefresh;

    private void fetchData(boolean isRefresh) {
        mIsRefresh = isRefresh;
        if (isRefresh) {
            mLastIndex = 1;
        }
        new AsyncTask<Void, Void, Void>() {

            private List<Weibo.WeiboBean> weibo;

            @Override
            protected Void doInBackground(Void... voids) {
                SystemClock.sleep(3000);
                if (mLastIndex <= 3) {
                    // 加载微博数据
                    String json = GlobalUtils.readAssets("weibo_list.json");
                    Gson gson = new Gson();
                    weibo = gson.fromJson(json, Weibo.class).getWeibo();
                } else {
                    weibo = new ArrayList<>();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if (mIsRefresh) {
                    mAdapter.setNewData(weibo);
                    mSwipeRefresh.setRefreshing(false);
                    mAdapter.setEnableLoadMore(true);
                } else {
                    if (weibo != null) {
                        if (weibo.size() == 0) {
                            mAdapter.loadMoreEnd();
                        } else {
                            mAdapter.addData(weibo);
                            mAdapter.loadMoreComplete();
                        }
                    }
                }
                mLastIndex++;
            }
        }.execute();
    }

    @Override
    public void onRefresh() {
        mAdapter.setEnableLoadMore(false);
        fetchData(true);
    }

    @Override
    public void onLoadMoreRequested() {
        if (mSwipeRefresh != null) {
            mSwipeRefresh.setEnabled(false);
            fetchData(false);
            mSwipeRefresh.setEnabled(true);
        }
    }
}

主要的逻辑代码已经完成,需要资源的请看git

https://gitee.com/huangxiaoguo/WeiBoLieBiaoShiXian

©️2020 CSDN 皮肤主题: Age of Ai 设计师:meimeiellie 返回首页