看到这些博客的时候,相信小伙伴们已经看了不少的有关于Android Jetpack的知识了,关于Jetpack的原理,有些文章讲的很好,这里就不重复了,此系列的博客,旨在通过一些很简单的小demo,和大家一起熟悉最基本的用法~
Android Jetpack -- Lifecycle
Android Jetpack -- ViewModel & LiveData
Android Jetpack -- paging & room
Android Jetpack -- navigation
项目git地址:https://github.com/zhangtiansimple/jetpack_demo
------------------------------------------------------------------------------------------------------------------------
相比较于前面两篇博客介绍的内容,paging的使用稍有复杂,所以本篇不以小例子开头,先来看paging里重要的三个类。
1.DataSource 数据源,数据的改变会驱动列表的更新。
2.PageList 核心类,负责分页加载的一些配置,例如第一次加载多少,每页加载多少等等。
3.PagedListAdapter 负责UI的展示逻辑
DataSource在创建数据源的时候,实际上是通过内部工厂类来创建的
public abstract static class Factory {
public abstract DataSource create();
}
数据源一般有本地数据和网络数据,这里选用room来作为数据源,一来熟悉jetpack组件,二来体会room和paging的原生支持。
@Dao
interface GirlDao {
@Query("SELECT * FROM Girl ORDER BY name COLLATE NOCASE ASC")
fun getAllGirl(): DataSource.Factory
@Insert
fun insert(students: List)
}
数据实体类
@Entity
data class Girl(
@PrimaryKey(autoGenerate = true) val id: Int,
val name: String
)
数据库类
@Database(entities = arrayOf(Girl::class), version = 1)
abstract class GirlDB : RoomDatabase() {
abstract fun girlDao(): GirlDao
companion object {
private var instance: GirlDB? = null
@Synchronized
fun get(context: Context): GirlDB {
if (instance == null) {
instance = Room.databaseBuilder(
context.applicationContext,
GirlDB::class.java, "GirlDateBase"
).addCallback(object : RoomDatabase.Callback() {
override fun onCreate(db: SupportSQLiteDatabase) {
ioThread {
get(context).girlDao().insert(
GIRL_DATA.map {
Girl(
id = 0,
name = it
)
})
}
}
}).build()
}
return instance!!
}
}
}
private val GIRL_DATA = arrayListOf(
"Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam", "Abondance", "Ackawi",
"Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu", "Airag", "Airedale",
"Aisy Cendre", "Allgauer Emmentaler", "Alverca", "Ambert", "American Cheese",
"Ami du Chambertin", "Anejo Enchilado", "Anneau du Vic-Bilh", "Anthoriro", "Appenzell",
"Aragon", "Ardi Gasna", "Ardrahan", "Armenian String", "Aromes au Gene de Marc",
"Asadero", "Asiago", "Aubisque Pyrenees", "Autun", "Avaxtskyr", "Baby Swiss",
"Babybel", "Baguette Laonnaise", "Bakers", "Baladi", "Balaton", "Bandal", "Banon",
"Barry's Bay Cheddar", "Basing", "Basket Cheese", "Bath Cheese", "Bavarian Bergkase",
"Baylough", "Beaufort", "Beauvoorde", "Beenleigh Blue", "Beer Cheese", "Bel Paese",
"Bergader", "Bergere Bleue", "Berkswell", "Beyaz Peynir", "Bierkase", "Bishop Kennedy",
"Blarney", "Bleu d'Auvergne", "Bleu de Gex", "Bleu de Laqueuille",
"Bleu de Septmoncel", "Bleu Des Causses", "Blue", "Blue Castello", "Blue Rathgore",
"Blue Vein (Australian)", "Blue Vein Cheeses", "Bocconcini", "Bocconcini (Australian)"
)
创建viewModel并配置PageList
class GirlViewModel(app: Application) : AndroidViewModel(app) {
val dao = GirlDB.get(app).girlDao()
val allGirls = LivePagedListBuilder(
dao.getAllGirl(), PagedList.Config.Builder()
.setPageSize(PAGE_SIZE) //配置分页加载的数量
.setEnablePlaceholders(ENABLE_PLACEHOLDERS) //配置是否启动PlaceHolders
.setInitialLoadSizeHint(PAGE_SIZE) //初始化加载的数量
.build()
).build()
companion object {
private const val PAGE_SIZE = 15
private const val ENABLE_PLACEHOLDERS = false
}
}
Activity显示数据
class PagingActivity : AppCompatActivity() {
private val viewModel by lazy(LazyThreadSafetyMode.NONE) {
ViewModelProviders.of(this, object : ViewModelProvider.Factory {
override fun create(modelClass: Class): T = GirlViewModel(application) as T
}).get(GirlViewModel::class.java)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_paging)
val adapter = GirlAdapter()
recyclerView.adapter = adapter
recyclerView.layoutManager = LinearLayoutManager(this)
viewModel.allGirls.observe(this, Observer {
adapter.submitList(it)
})
}
}