Jetpack Paging的简单使用

效果如图

引入

apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"

    defaultConfig {
        applicationId "com.lk.calendar"
        minSdkVersion 26
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    compileOptions {
        sourceCompatibility = 1.8
        targetCompatibility = 1.8
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation "androidx.paging:paging-runtime:2.1.2"
}

生成数据

package com.lk.calendar;

import androidx.annotation.NonNull;
import androidx.paging.PageKeyedDataSource;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lkuan
 * Create on 2020/5/28-17:45.
 **/
public class CalendarDataSource extends PageKeyedDataSource<LocalDate, Integer> {

    @Override
    public void loadInitial(@NonNull LoadInitialParams<LocalDate> params, @NonNull LoadInitialCallback<LocalDate, Integer> callback) {
        LocalDate nowDate = LocalDate.now();

        int preDays = nowDate.withDayOfMonth(1).getDayOfWeek().getValue();
        List<Integer> data = new ArrayList<>();
        LocalDate monthDate = LocalDate.of(nowDate.getYear(), nowDate.getMonth(), 1);
        monthDate = monthDate.minusDays(preDays - 1);
        for (int i = 0; i < 42; i++) {
            data.add(monthDate.getDayOfMonth());
            monthDate = monthDate.plusDays(1);
        }

        LocalDate prevDate = nowDate.withDayOfMonth(1).minusDays(preDays - 1).minusDays(42);
        LocalDate nextDate = prevDate.plusDays(84);

        callback.onResult(data, 0, 42, prevDate, nextDate);
    }

    @Override
    public void loadBefore(@NonNull LoadParams<LocalDate> params, @NonNull LoadCallback<LocalDate, Integer> callback) {
        LocalDate beforeDate = params.key;
        callback.onResult(fillData(beforeDate), beforeDate.minusDays(42));
    }

    @Override
    public void loadAfter(@NonNull LoadParams<LocalDate> params, @NonNull LoadCallback<LocalDate, Integer> callback) {
        LocalDate afterDate = params.key;
        callback.onResult(fillData(afterDate), afterDate.plusDays(42));
    }

    private List<Integer> fillData(LocalDate localDate) {
        List<Integer> data = new ArrayList<>();
        for (int i = 0; i < 42; i++) {
            data.add(localDate.getDayOfMonth());
            localDate = localDate.plusDays(1);
        }
        return data;
    }
}

package com.lk.calendar;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;
import androidx.paging.DataSource;

import java.time.LocalDate;

/**
 * @author lkuan
 * Create on 2020/5/28-17:48.
 **/
public class CalendarDataSourceFactory extends DataSource.Factory<LocalDate, Integer> {

    private MutableLiveData<CalendarDataSource> mSourceLiveData = new MutableLiveData<>();

    @NonNull
    @Override
    public DataSource<LocalDate, Integer> create() {
        CalendarDataSource dataSource = new CalendarDataSource();
        mSourceLiveData.postValue(dataSource);
        return dataSource;
    }
}

适配器

package com.lk.calendar;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.paging.PagedListAdapter;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.RecyclerView;

/**
 * @author lkuan
 * Create on 2020/5/28-18:00.
 **/
public class CalendarAdapter extends PagedListAdapter<Integer, CalendarAdapter.CalendarViewHolder> {

    public CalendarAdapter() {
        super(mDiffCallback);
    }

    @NonNull
    @Override
    public CalendarViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_1, parent, false);
        // 只显示6行
        int parentHeight = parent.getHeight();
        ViewGroup.LayoutParams lp = itemView.getLayoutParams();
        lp.height = parentHeight / 6;
        itemView.setLayoutParams(lp);
        return new CalendarViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull CalendarViewHolder holder, int position) {
        holder.item.setText(String.valueOf(getItem(position)));
    }

    static class CalendarViewHolder extends RecyclerView.ViewHolder {
        private TextView item;

        private CalendarViewHolder(@NonNull View itemView) {
            super(itemView);
            item = itemView.findViewById(android.R.id.text1);
        }
    }

    private static DiffUtil.ItemCallback<Integer> mDiffCallback = new DiffUtil.ItemCallback<Integer>() {
        @Override
        public boolean areItemsTheSame(@NonNull Integer oldItem, @NonNull Integer newItem) {
            return false;
        }

        @Override
        public boolean areContentsTheSame(@NonNull Integer oldItem, @NonNull Integer newItem) {
            return false;
        }
    };
}

主布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".CalendarActivity">

    <include layout="@layout/weekdays" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/calendar_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

使用

package com.lk.calendar;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.paging.LivePagedListBuilder;
import androidx.paging.PagedList;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;

import java.time.LocalDate;

public class CalendarActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calendar);
        RecyclerView recyclerView = findViewById(R.id.calendar_list);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 7));
        PagedList.Config config = new PagedList.Config.Builder()
                .setPageSize(42)
                .setEnablePlaceholders(false)
                .setInitialLoadSizeHint(42)
                .build();
        LiveData<PagedList<Integer>> liveData = new LivePagedListBuilder<LocalDate, Integer>(new CalendarDataSourceFactory(), config).build();
        CalendarAdapter adapter = new CalendarAdapter();
        recyclerView.setAdapter(adapter);
        liveData.observe(this, new Observer<PagedList<Integer>>() {
            @Override
            public void onChanged(PagedList<Integer> integers) {
                adapter.submitList(integers);
            }
        });
    }
}

源码

Mok目录calendar

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值