Jetpack Paging的简单使用

模仿AOSP日历月份页面

  • 引入
  • 生成数据
  • 适配器
  • 主布局
  • 使用
  • 源码

Jetpack Paging的简单使用_第1张图片

引入

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 {

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

        int preDays = nowDate.withDayOfMonth(1).getDayOfWeek().getValue();
        List 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 params, @NonNull LoadCallback callback) {
        LocalDate beforeDate = params.key;
        callback.onResult(fillData(beforeDate), beforeDate.minusDays(42));
    }

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

    private List fillData(LocalDate localDate) {
        List 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 {

    private MutableLiveData mSourceLiveData = new MutableLiveData<>();

    @NonNull
    @Override
    public DataSource 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 {

    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 mDiffCallback = new DiffUtil.ItemCallback() {
        @Override
        public boolean areItemsTheSame(@NonNull Integer oldItem, @NonNull Integer newItem) {
            return false;
        }

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

主布局




    

    

使用

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> liveData = new LivePagedListBuilder(new CalendarDataSourceFactory(), config).build();
        CalendarAdapter adapter = new CalendarAdapter();
        recyclerView.setAdapter(adapter);
        liveData.observe(this, new Observer>() {
            @Override
            public void onChanged(PagedList integers) {
                adapter.submitList(integers);
            }
        });
    }
}

源码

Mok目录calendar

你可能感兴趣的:(Android)