《安卓-深入浅出MVVM教程》应用篇-06 Load More (加载更多)

简介

背景

这几年 MVP 架构在安卓界非常流行,几乎已经成为主流框架,它让业务逻辑 和 UI操作相对独立,使得代码结构更清晰。


MVVM 在前端火得一塌糊涂,而在安卓这边却基本没见到几个人在用,看到介绍 MVVM 也最多是讲 DataBinding 或 介绍思想的。偶尔看到几篇提到应用的,还是对谷歌官网的Architecture Components 文章的翻译。

相信大家看别人博客或官方文档的时候,总会碰到一些坑。要么入门教程写得太复杂(无力吐槽,前面写一堆原理,各种高大上的图,然并卵,到实践部分一笔带过,你确定真的是入门教程吗)。要么就是简单得就是一个 hello world,然后就没有下文了(看了想骂人)。


实在看不下去的我,决定插手你的人生。

目录

《安卓-深入浅出MVVM教程》大致分两部分:应用篇、原理篇。
采用循序渐进方式,内容深入浅出,符合人类学习规律,希望大家用最少时间掌握 MVVM。

应用篇:

01 Hello MVVM (快速入门)
02 Repository (数据仓库)
03 Cache (本地缓存)
04 State Lcee (加载/空/错误/内容视图)
05 Simple Data Source (简单的数据源)
06 Load More (加载更多)
07 DataBinding (数据与视图绑定)
08 RxJava2
09 Dragger2
10 Abstract (抽象)
11 Demo (例子)
12-n 待定(欢迎 github 提建议)

原理篇

01 MyLiveData(最简单的LiveData)
02-n 待定(并不是解读源码,那样太无聊了,打算带你从0撸一个 Architecture)

关于提问

本人水平和精力有限,如果有大佬发现哪里写错了或有好的建议,欢迎在本教程附带的 github仓库 提issue。
What?为什么不在博客留言?考虑到国内转载基本无视版权的情况,一般来说你都不是在源出处看到这篇文章,所以留言我也一般是看不到的。

教程附带代码

https://github.com/ittianyu/MVVM

应用篇放在 app 模块下,原理篇放在 implementation 模块下。
每一节代码采用不同包名,相互独立。

前言

上一节是 04 的变体,这一节因为改动太大,所以从 0 开始。
这次的案例是从 github 上获取仓库列表,并展示仓库名 和 star 数量。

环境

root build.gradle

allprojects {
    repositories {
        jcenter()
        maven { url 'https://maven.google.com' }
    }
}

ext {
    lifecycle = '1.0.0-rc1'
    lifecycleRuntime = '1.0.3'
    room = '1.0.0-rc1'
    supportLibraryVersion = '26.+'
}

app bulid.gradle

dependencies {
...
    // Lifecycles, LiveData and ViewModel
    compile "android.arch.lifecycle:runtime:$rootProject.lifecycleRuntime"
    compile "android.arch.lifecycle:extensions:$rootProject.lifecycle"
    annotationProcessor "android.arch.lifecycle:compiler:$rootProject.lifecycle"

    // room
    compile "android.arch.persistence.room:runtime:$rootProject.room"
    annotationProcessor "android.arch.persistence.room:compiler:$rootProject.room"

    // retrofit
    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.squareup.retrofit2:converter-gson:2.3.0'

}

manifest

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Model

Bean

先把之前写过的一些实体类定义出来

Lcee

public class Lcee<T> {
    public final Status status;
    public final T data;
    public final Throwable error;

    private Lcee(Status status, T data, Throwable error) {
        this.status = status;
        this.data = data;
        this.error = error;
    }

    public static <T> Lcee<T> content(T data) {
        return new Lcee<>(Status.Content, data, null);
    }

    public static <T> Lcee<T> error(T data, Throwable error) {
        return new Lcee<>(Status.Error, data, error);
    }
    public static <T> Lcee<T> error(Throwable error) {
        return error(null, error);
    }

    public static <T> Lcee<T> empty(T data) {
        return new Lcee<>(Status.Empty, data, null);
    }
    public static <T> Lcee<T> empty() {
        return empty(null);
    }

    public static <T> Lcee<T> loading(T data) {
        return new Lcee<>(Status.Loading, data, null);
    }
    public static <T> Lcee<T> loading() {
        return loading(null);
    }

}

Status

public enum Status {
    Loading,
    Content,
    Empty,
    Error,
}

api

https://api.github.com/search/repositories?q=tetris+language:assembly&sort=stars&order=desc

返回数据就不写了(太长了),直接访问一下就能看到。

Bean

根据 Api,用 GsonFormatter 生成实体类,或者自己手写也行。我这里之后又把内部类提出来了。

Projects

public class Projects implements Serializable {
    private int total_count;
    private boolean incomplete_results;
    private List<ProjectItem> items;
... getter and setter ...
}

ProjectItem

public class ProjectItem {
    private int id;
    private String name;
    private String full_name;
    private ProjectOwner owner;
    @SerializedName("private")
    private boolean privateX;
    private String html_url;
    private String description;
    private boolean fork;
    private String url;
    private String forks_url;
    private String keys_url;
    private String collaborators_url;
    private String teams_url;
    private String hooks_url;
    private String issue_events_url;
    private String events_url;
    private String assignees_url;
    private String branches_url;
    private String tags_url;
    private String blobs_url;
    private String git_tags_url;
    private String git_refs_url;
    private String trees_url;
    private String statuses_url;
    private String languages_url;
    private String stargazers_url;
    private String contributors_url;
    private String subscribers_url;
    private String subscription_url;
    private String commits_url;
    private String git_commits_url;
    private String comments_url;
    private String issue_comment_url;
    private String contents_url;
    private String compare_url;
    private String merges_url;
    private String archive_url;
    private String downloads_url;
    private String issues_url;
    private String pulls_url;
    private String milestones_url;
    private String notifications_url;
    private String labels_url;
    private String releases_url;
    private String deployments_url;
    private String created_at;
    private String updated_at;
    private String pushed_at;
    private String git_url;
    private String ssh_url;
    private String clone_url;
    private String svn_url;
    private String homepage;
    private int size;
    private int stargazers_count;
    private int watchers_count;
    private String language;
    private boolean has_issues;
    private boolean has_projects;
    private boolean has_downloads;
    private boolean has_wiki;
    private boolean has_pages;
    private int forks_count;
    private String mirror_url;
    private int open_issues_count;
    private int forks;
    private int open_issues;
    private int watchers;
    private String default_branch;
    private double score;
... getter and setter ...
}

ProjectOwner

public class ProjectOwner {
    private String login;
    private int id;
    private String avatar_url;
    private String gravatar_id;
    private String url;
    private String html_url;
    private String followers_url;
    private String following_url;
    private String gists_url;
    private String starred_url;
    private String subscriptions_url;
    private String organizations_url;
    private String repos_url;
    private String events_url;
    private String received_events_url;
    private String type;
    private boolean site_admin;
... getter and setter ...
}

View

有了数据模型,接下来要展示 View 了。
事实上下面写的这些都不是本节的重点,但又不得不写,所以不做过多解释。

xml

和之前一样,4 种 视图,内容视图为 SwipeRefreshLayout 包裹 RecyclerView

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/v_root"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/v_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

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

            <android.support.v7.widget.RecyclerView
                android:id="@+id/rv"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>

        </android.support.v4.widget.SwipeRefreshLayout>

    </FrameLayout>

    <FrameLayout
        android:id="@+id/v_error"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center"
            android:text="Network error, click to reload" />

    </FrameLayout>

    <FrameLayout
        android:id="@+id/v_empty"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center"
            android:text="User not exist" />

    </FrameLayout>

    <FrameLayout
        android:id="@+id/v_loading"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ProgressBar
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center" />

    </FrameLayout>

</FrameLayout>

ProjectsActivity

先初始化 View,并绑定 UI 事件。
先定义两个空方法 reload loadMore

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.f_activity_projects);
    initView();
    initData();
    initEvent();
}

private void initView() {
    vContent = findViewById(R.id.v_content);
    vError = findViewById(R.id.v_error);
    vLoading = findViewById(R.id.v_loading);
    vEmpty = findViewById(R.id.v_empty);

    srl = (SwipeRefreshLayout) findViewById(R.id.srl);
    rv = (RecyclerView) findViewById(R.id.rv);

    rv.setLayoutManager(new LinearLayoutManager(this));
    projectsAdapter = new ProjectsAdapter();
    rv.setAdapter(projectsAdapter);
}

private void initData() {
}

private void initEvent() {
    View.OnClickListener reloadClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            reload();
        }
    };
    vError.setOnClickListener(reloadClickListener);
    vEmpty.setOnClickListener(reloadClickListener);

    // refresh
    srl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            if (isLoading()) {
                srl.setRefreshing(false);
                return;
            }
            reload();
        }
    });

    // load more
    rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
        public int mLastVisibleItemPosition;

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
            if (layoutManager instanceof LinearLayoutManager) {
                mLastVisibleItemPosition = ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition();
            }
            if (projectsAdapter == null)
                return;

            if (newState == RecyclerView.SCROLL_STATE_IDLE
                    && mLastVisibleItemPosition + 1 == projectsAdapter.getItemCount()) {

                if (isLoading())
                    return;
                loadMore();
            }
        }
    });
}

private void reload() {

}

private void loadMore() {

}

private void isLoading() {

}

ProjectsAdapter

上面初始化 rv 时用到了 ProjectsAdapter,其实就是每一行展示 name 和 star 数量。

public class ProjectsAdapter extends RecyclerView.Adapter<ProjectsAdapter.ProjectViewHolder> {
    private List<ProjectItem> data = new ArrayList<>();

    public ProjectsAdapter() {
    }

    public ProjectsAdapter(List<ProjectItem> data) {
        this.data = data;
    }

    @Override
    public ProjectViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.f_item_project, parent, false);
        return new ProjectViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ProjectViewHolder holder, int position) {
        ProjectItem item = getData().get(position);
        holder.tvName.setText(item.getFull_name());
        holder.tvStar.setText(item.getStargazers_count() + " star");
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    public void setData(List<ProjectItem> data) {
        if (null != data)
            this.data = data;
        else
            this.data.clear();

        notifyDataSetChanged();
    }

    public void addData(List<ProjectItem> data) {
        if (null == data || data.size() == 0)
            return;

        int index = getItemCount();
        this.data.addAll(data);
        notifyItemRangeInserted(index, data.size());
    }


    public static class ProjectViewHolder extends RecyclerView.ViewHolder {
        TextView tvName;
        TextView tvStar;

        public ProjectViewHolder(View itemView) {
            super(itemView);

            tvName = itemView.findViewById(R.id.tv_name);
            tvStar = itemView.findViewById(R.id.tv_star);
        }
    }

    public List<ProjectItem> getData() {
        return data;
    }

}

f_item_project.xml

list 的 item 非常简单,就是水平的两个 TextView

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:paddingBottom="8dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="8dp">

    <TextView
        android:id="@+id/tv_name"
        android:text="name/project"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:maxLines="1"
        android:layout_marginRight="8dp"
        android:textColor="@android:color/black"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/tv_star"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="99999" />

</LinearLayout>

Model DataSource

UI 的基本代码已经有了,就差和 ViewModel 绑定了。
为了便于 ViewModel 调用数据,我们还需要写 DataSource
而 DataSource 前面几节已经详细的讲过了,这里不过多解释。

ProjectDataSource

public interface ProjectDataSource {
    LiveData<Lcee<Projects>> queryProjects(int page);
}

LocalProjectDataSource

在实体类上加上注解,但实际上还会面临两个问题

  1. 找不到合适的主键。
    仔细想一下,如果直接存 Projects,最关键的还是 page,所以这里加入一个 page 作为主键。
  2. List<ProjectItem> 不容易存储。
    使用外键来关联太麻烦了,所以这里为了方便,直接转化为 json 后再存储。也就是 Ignore 这个字段,然后加一个 private String itemsJson;

实际上,完全有其他选择,比如存 ProjectItem 而不是 Projects。但这里为了简单的演示 LoadMore,就不在这里大做文章。

@Entity(tableName = "projects")
public class Projects implements Serializable {
...
    @Ignore
    private List<ProjectItem> items;

    // used for local cache
    @PrimaryKey
    private int page;

    @ColumnInfo(name = "items")
    private String itemsJson;
...
}

Dao

@Dao
public interface ProjectsDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)// cache need update
    Long add(Projects projects);

    @Query("select * from projects where page=:page")
    LiveData<Projects> queryProjects(int page);
}

@Database(entities = {Projects.class}, version = 1, exportSchema = false)
public abstract class DB extends RoomDatabase {
    public abstract ProjectsDao getProjectsDao();

}

DBHelper

public class DBHelper {
    private static final DBHelper instance = new DBHelper();
    private static final String DATABASE_NAME = "f_load_more";

    private DBHelper() {

    }

    public static DBHelper getInstance() {
        return instance;
    }

    private DB db;

    public void init(Context context) {
        db = Room.databaseBuilder(context.getApplicationContext(), DB.class, DATABASE_NAME).build();
    }

    public DB getDb() {
        return db;
    }
}

Service

接口

public interface ProjectsService {
    LiveData<Long> add(Projects projects);

    /**
     *
     * @param page start from 1
     * @return
     */
    LiveData<Projects> queryProjects(int page);
}

实现

public class ProjectsServiceImpl implements ProjectsService {
    private static final ProjectsServiceImpl instance = new ProjectsServiceImpl();

    private ProjectsServiceImpl() {
    }

    public static ProjectsServiceImpl getInstance() {
        return instance;
    }


    private ProjectsDao projectsDao = DBHelper.getInstance().getDb().getProjectsDao();

    @Override
    public LiveData<Long> add(final Projects projects) {
        // transfer long to LiveData<Long>
        final MutableLiveData<Long> data = new MutableLiveData<>();
        new AsyncTask<Void, Void, Long>() {
            @Override
            protected Long doInBackground(Void... voids) {
                return projectsDao.add(projects);
            }

            @Override
            protected void onPostExecute(Long rowId) {
                data.setValue(rowId);
            }
        }.execute();
        return data;
    }

    @Override
    public LiveData<Projects> queryProjects(int page) {
        return projectsDao.queryProjects(page);
    }

}

LocalProjectDataSource

注意,因为数据库存储的关系,在存之前先转化为 json projects.itemsToJson();
在取的时候,要从 json 转化为 bean
projects.itemsFromJson();

public class LocalProjectDataSource implements ProjectDataSource {
    private static final LocalProjectDataSource instance = new LocalProjectDataSource();

    private LocalProjectDataSource() {
    }

    public static LocalProjectDataSource getInstance() {
        return instance;
    }


    private ProjectsService projectsService = ProjectsServiceImpl.getInstance();

    public LiveData<Long> addProjects(Projects projects) {
        // format items to json
        projects.itemsToJson();
        return projectsService.add(projects);
    }

    @Override
    public LiveData<Lcee<Projects>> queryProjects(int page) {
        final MediatorLiveData<Lcee<Projects>> data = new MediatorLiveData<>();
        data.setValue(Lcee.<Projects>loading());

        data.addSource(projectsService.queryProjects(page), new Observer<Projects>() {
            @Override
            public void onChanged(@Nullable Projects projects) {
                if (null == projects) {
                    data.setValue(Lcee.<Projects>empty());
                } else {
                    // parse items from json
                    projects.itemsFromJson();
                    data.setValue(Lcee.content(projects));
                }
            }
        });
        return data;
    }
}

所以在 Projects 加上这两个方法

public void itemsToJson() {
    if (items == null)
        items = Collections.emptyList();
    itemsJson = new Gson().toJson(items);
}

public void itemsFromJson() {
    if (TextUtils.isEmpty(itemsJson))
        return;
    items = new Gson().fromJson(itemsJson, new TypeToken<List<ProjectItem>>(){}.getType());
}

RemoteProjectDataSource

RetrofitFactory

public class RetrofitFactory {
    private static OkHttpClient client;
    private static Retrofit retrofit;

    private static final String HOST = "https://api.github.com";

    static {
        client = new OkHttpClient.Builder()
                .connectTimeout(9, TimeUnit.SECONDS)
                .build();

        retrofit = new Retrofit.Builder()
                .baseUrl(HOST)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    public static Retrofit getInstance() {
        return retrofit;
    }
}

ProjectApi

public interface ProjectApi {
    @GET("/search/repositories?q=tetris+language:assembly&sort=stars&order=desc")
    Call<Projects> queryProjects(@Query("page") int page);
}

RemoteProjectDataSource

这里需要注意,在存到本地源的时候,要先 projects.setPage(page); 设置 page,也就是主键

public class RemoteProjectDataSource implements ProjectDataSource {
    private static final RemoteProjectDataSource instance = new RemoteProjectDataSource();

    private RemoteProjectDataSource() {
    }

    public static RemoteProjectDataSource getInstance() {
        return instance;
    }


    private ProjectApi projectApi = RetrofitFactory.getInstance().create(ProjectApi.class);


    @Override
    public LiveData<Lcee<Projects>> queryProjects(final int page) {
        final MutableLiveData<Lcee<Projects>> data = new MutableLiveData<>();
        data.setValue(Lcee.<Projects>loading());

        projectApi.queryProjects(page)
                .enqueue(new Callback<Projects>() {
                    @Override
                    public void onResponse(Call<Projects> call, Response<Projects> response) {
                        Projects projects = response.body();
                        if (null == projects) {
                            data.setValue(Lcee.<Projects>empty());
                            return;
                        }
                        data.setValue(Lcee.content(projects));
                        // update cache
                        projects.setPage(page);// must set page before save to db
                        LocalProjectDataSource.getInstance().addProjects(projects);
                    }

                    @Override
                    public void onFailure(Call<Projects> call, Throwable t) {
                        t.printStackTrace();
                        data.setValue(Lcee.<Projects>error(t));
                    }
                });
        return data;
    }
}

ProjectsRepository

public class ProjectsRepository {
    private static final ProjectsRepository instance = new ProjectsRepository();
    private ProjectsRepository() {
    }
    public static ProjectsRepository getInstance() {
        return instance;
    }


    private Context context;
    private ProjectDataSource remoteProjectDataSource = RemoteProjectDataSource.getInstance();
    private ProjectDataSource localProjectDataSource = LocalProjectDataSource.getInstance();

    public void init(Context context) {
        this.context = context.getApplicationContext();
    }

    public LiveData<Lcee<Projects>> getProjects(int page) {
        if (NetworkUtils.isConnected(context)) {
            return remoteProjectDataSource.queryProjects(page);
        } else {
            return localProjectDataSource.queryProjects(page);
        }
    }
}

ViewModel

ProjectsViewModel

public class ProjectsViewModel extends ViewModel {
    private ProjectsRepository projectsRepository = ProjectsRepository.getInstance();
    private MutableLiveData<Integer> ldPage;;
    private LiveData<Lcee<Projects>> ldProjects;

    public LiveData<Lcee<Projects>> getProjects() {
        if (null == ldProjects) {
            ldPage = new MutableLiveData<>();
            ldProjects = Transformations.switchMap(ldPage, new Function<Integer, LiveData<Lcee<Projects>>>() {
                @Override
                public LiveData<Lcee<Projects>> apply(Integer page) {
                    return projectsRepository.getProjects(page);
                }
            });
        }
        return ldProjects;
    }

    public void reload() {
        ldPage.setValue(1);
    }

    public void loadMore(int currentCount) {
        ldPage.setValue(PageUtils.getPage(currentCount));
    }
}

PageUtils

public class PageUtils {
    private static final int COUNT_PER_PAGE = 30;

    public static int getPage(int count) {
        int page = count / COUNT_PER_PAGE + 1;
        if (count % COUNT_PER_PAGE > 0)
            page++;
        return page;
    }
}

View Bind With ViewModel

private void initData() {
    DBHelper.getInstance().init(this);
    ProjectsRepository.getInstance().init(this);

    projectsViewModel = ViewModelProviders.of(this).get(ProjectsViewModel.class);
    projectsViewModel.getProjects().observe(this, new Observer<Lcee<Projects>>() {
        @Override
        public void onChanged(@Nullable Lcee<Projects> data) {
            updateView(data);
        }
    });

    reload();
}

private void reload() {
    projectsViewModel.reload();
}

private void loadMore() {
    projectsViewModel.loadMore(projectsAdapter.getItemCount());
}


private void updateView(Lcee<Projects> lcee) {
    status = lcee.status;
    switch (lcee.status) {
        case Content: {
            updateContentView(lcee.data);
            break;
        }
        case Empty: {
            updateEmptyView();
            break;
        }
        case Error: {
            updateErrorView();
            break;
        }
        case Loading: {
            updateLoadingView();
            break;
        }
    }
}

到这里为止,似乎和之前没什么不同。

Loading Status

接下来就是本节的重点了。

Loading State 还可以再分
仔细想一下,加载状态其实是可以分为 刷新、加载更多、初始化加载

Loading State 的区别是 UI 操作
但需要注意的是,这三种加载状态,对于数据本身来说,是很难区分的,也就是说都是加载状态,数据本身怎么会知道是刷新还是加载更多呢。

而区分这几种加载状态的是 UI 操作,比如用户下拉刷新,所以加载状态就是 Refreshing,而用户上滑加载更多则是 LoadMore。

非要把三种加载状态给数据本身,就需要请求时把加载类型作为参数传给 ViewModel,这显然是破坏性行为。

定义独立的 Load Status

因为这几种状态多见于 List 中,所以姑且命名为 ListStatus

public enum ListStatus {
    Refreshing,
    LoadingMore,
    Content,
}

记录 ListStatus

在刷新操作 和 加载更多操作中,记录当前的 ListStatus

listStatus = ListStatus.Refreshing;
listStatus = ListStatus.LoadingMore;

// refresh
srl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
    @Override
    public void onRefresh() {
        if (isLoading()) {
            srl.setRefreshing(false);
            return;
        }
        listStatus = ListStatus.Refreshing;
        reload();
    }
});


// load more
rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
    public int mLastVisibleItemPosition;

    @Override
    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
        if (layoutManager instanceof LinearLayoutManager) {
            mLastVisibleItemPosition = ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition();
        }
        if (projectsAdapter == null)
            return;

        if (newState == RecyclerView.SCROLL_STATE_IDLE
                && mLastVisibleItemPosition + 1 == projectsAdapter.getItemCount()) {

            if (isLoading())
                return;
            listStatus = ListStatus.LoadingMore;
            loadMore();
        }
    }
});

updateContentView

因为有了独立的 ListStatus,所以在渲染 Content 时,也要考虑。

如果是 LoadingMore,则往 adapter 中加入数据。
如果是 Refreshing,则停止 下拉刷新UI
否则 给 adapter 重新设置数据

private void updateContentView(Projects projects) {
    switch (listStatus) {
        case LoadingMore: {
            projectsAdapter.addData(projects.getItems());
            // todo load more complete

            break;
        }
        case Refreshing: {
            srl.setRefreshing(false);
            break;
        }
        default: {
            showContent();
            projectsAdapter.setData(projects.getItems());
            break;
        }
    }
}

updateEmptyView

空视图也是一样,如果下拉刷新得到结果为空,则停止刷新,并显示空视图,如果是加载更多返回空,则说明没有更多数据了,应该更新 List 的 Footer(这里省事我没加 Footer)

private void updateEmptyView() {
    switch (listStatus) {
        case LoadingMore: {
            // todo no more data

            break;
        }
        case Refreshing: {
            srl.setRefreshing(false);
            showEmpty();
            break;
        }
        default: {
            showEmpty();
            break;
        }
    }
}

updateErrorView

private void updateErrorView() {
    switch (listStatus) {
        case LoadingMore: {
            // todo load more error

            break;
        }
        case Refreshing: {
            srl.setRefreshing(false);
            Toast.makeText(this, "Refresh failed", Toast.LENGTH_SHORT).show();
            break;
        }
        default: {
            showError();
            break;
        }
    }
}

updateLoadingView

private void updateLoadingView() {
    switch (listStatus) {
        case LoadingMore: {
            // todo show loading more view in list footer

            break;
        }
        case Refreshing: {

            break;
        }
        default: {
            showLoading();
            break;
        }
    }
}

其他

private void showContent() {
    vContent.setVisibility(View.VISIBLE);
    vEmpty.setVisibility(View.GONE);
    vError.setVisibility(View.GONE);
    vLoading.setVisibility(View.GONE);
}

private void showEmpty() {
    vContent.setVisibility(View.GONE);
    vEmpty.setVisibility(View.VISIBLE);
    vError.setVisibility(View.GONE);
    vLoading.setVisibility(View.GONE);
}

private void showError() {
    vContent.setVisibility(View.GONE);
    vEmpty.setVisibility(View.GONE);
    vError.setVisibility(View.VISIBLE);
    vLoading.setVisibility(View.GONE);
}

private void showLoading() {
    vContent.setVisibility(View.GONE);
    vEmpty.setVisibility(View.GONE);
    vError.setVisibility(View.GONE);
    vLoading.setVisibility(View.VISIBLE);
}

private boolean isLoading() {
    return status == Status.Loading;
}

总结

倒吸一口冷气,这篇幅有点长,因为是从 0 开始,很多代码都是大家熟悉的。
重点要掌握的是,View 层里面的 ListStatus 状态,以及根据 ListStatus 和 Status 来渲染界面。

到这里大家可以放轻松了,因为本系列教程中最复杂的 UI 逻辑已经搞定了。
但别高兴得太早,老司机要开始飚车了,大家坐稳扶好。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,723评论 6 481
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,485评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 152,998评论 0 344
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,323评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,355评论 5 374
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,079评论 1 285
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,389评论 3 400
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,019评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,519评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,971评论 2 325
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,100评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,738评论 4 324
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,293评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,289评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,517评论 1 262
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,547评论 2 354
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,834评论 2 345

推荐阅读更多精彩内容