Android的架构组件

Olápovo,

谷歌在2017年I / O大会上宣布了Android平台。 Android的Kotlin e Architecture Components

Android实用程序和Android插件的使用可以从Android插件的安装到安装完毕,以及使用Java或Kotlin的最新版本。

Os Architecture Components的用法和样例:实现了应用程序的通用性,并简化了示例性的coms utils essas API。

ADICIONANDO作为副总裁

使用Android Studio 2.4 com或插件1.1.2来实现的功能。 您可以使用预览器来预览Android Studio 3.0的版本。 Crie um novo projeto包含了一个Kotlin e nomeie a Sua活动主体(即ListPeopleActivity)。 来自criado,vamos fazer,因为seguintes不存在任何问题。

buildscript { 
ext.gradle_version = '2.3.2'
ext.kotlin_version = '1.1.2-3'
ext.anko_version = '0.8.2'
ext.support_version = '25.3.1'
ext.arch_lifecycle_version = "1.0.0-alpha1"
ext.arch_room_version = "1.0.0-alpha1"
  repositories { 
jcenter()
}
  dependencies { 
classpath "com.android.tools.build:gradle:$gradle_version"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
allprojects {
repositories {
jcenter()
maven { url 'https://maven.google.com'
dependencies {
classpath "com.android.tools.build:gradle:$gradle_version"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
allprojects {
repositories {
jcenter()
maven { url 'https://maven.google.com'
}
mavenCentral()
}
}
}
mavenCentral()
}
}

Aqui criamos umasériedevariáveiscom作为无所不能的书目。 Issonãoéobrigatório,mas facilita a arquivo e evita erros e conflitos entreversõesdas bibliotecas。 Adicionamos,Gradle,Kotlin,Anko(在UI上具有便利性),finalmente支持库,生命周期内的dabliotecas de arquitetura。
Na listadedependências,alémdo gradle,addicionamos或Kotlin插件。 由fim,repositórios列表,devemos adicionar或“ maven.google.com”组成。

Agoraváatéo build.gradle domóduloda suaaplicaçãofa fasa os seguintes ajustes。

 apply plugin: 'com.android.application' 
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
 android { 
// Nada muda aqui...
}
 dependencies { 
compile fileTree(dir: 'libs', include: ['*.jar'])
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
compile "org.jetbrains.anko:anko-common:$anko_version"
compile "com.android.support:appcompat-v7:$support_version"
compile "com.android.support:design:$support_version"
compile "com.android.support:support-v4:$support_version"
compile "android.arch.lifecycle:runtime:$arch_lifecycle_version"
compile "android.arch.lifecycle:extensions:$arch_lifecycle_version"
compile "android.arch.persistence.room:runtime:$arch_room_version"
kapt "android.arch.lifecycle:compiler:$arch_lifecycle_version"
kapt "android.arch.persistence.room:compiler:$arch_room_version"
}

Alémdo plugin do Android,estamos aplicando o plugin do Kotlin扩展了对Kotlin的支持。 根据需要,将adicionamos todas命名为utilizaremos nesse projeto。 用Kotlin(科特林注释处理工具)替代“ annotationProcessor”。 波斯尼亚和黑塞哥维那(Perceba que utilizamos o kapt para)图书合集。 Isso deve ser feito para outras bibliotecas que fazem esse trabalho(Dagger,DataBinding等)。

DEFININDO O ACESSO AO BANCO

最简单的教程和入门指南,可以从比索的简单复制中受益,从头到尾的成本法则是免费的。 帕拉塔尔,一个经典的定义:

  import android.arch.persistence.room.Entity 
import
android.arch.persistence.room.Entity
import
android.arch.persistence.room.Entity
import
android.arch.persistence.room.PrimaryKey
import
android.arch.persistence.room.PrimaryKey
import
android.arch.persistence.room.PrimaryKey
import
java.io.Serializable
 @Entity 
data class
@Entity
data class
Person(
@PrimaryKey(autoGenerate = true ) var id: Long = 0L,
var firstName: String = "",
var lastName: String = "",
var age: Int = 0) : Serializable
Person(
@PrimaryKey(autoGenerate = true ) var id: Long = 0L,
var firstName: String = "",
var lastName: String = "",
var age: Int = 0) : Serializable

Criamos uma数据类anotada com @Entity ,持久性对象。 默认值是“ Todos osparâmetrostêmvalores”,而“ classes passe criar objetos dessa classe passando nenhumparâmetro”是默认值。 用户自定义类别的所有属性@PrimaryKey ,示例, eleserágerado autoamente ,entãodefinimos都是自动生成的。

Agora vamos定义了一个DAO,它是由ban com de bans de dados的possuiráosmétodospara的接口。

  import android.arch.lifecycle.LiveData 
import
android.arch.lifecycle.LiveData
import
android.arch.lifecycle.LiveData
import
android.arch.persistence.room.*
import
android.arch.persistence.room.*
import
android.arch.persistence.room.*
import
android.arch.persistence.room.OnConflictStrategy.IGNORE
 @Dao 
interface
@Dao
interface
PeopleDao {
@Insert(onConflict = IGNORE)
fun insertPerson(person: Person)
PeopleDao {
@Insert(onConflict = IGNORE)
fun insertPerson(person: Person)
  @Update 
fun updatePerson(person: Person)
  @Delete 
fun deletePerson(vararg people: Person)
  @Query("SELECT * FROM Person ORDER BY firstName") 
fun listAll(): LiveData<List>
}

Nossa界面estate anotada com @Dao e osmétodosde inserir,atualizar,exclir e listarestãoanotados尊敬的com @Insert@ Update@Delete e @Query 。 插入人(Person)可能会在IGNORE冲突定义中受到侵犯,因此不能立即加入或删除任何人。
可以重复使用,但不能删除deletePerson()允许使用临时模板或vararg 。 参与者之间的互感性listAll(),已从LiveData中获得了列表对象。
适用于inserido,alterado或excluído,listaseráautoamente atualizada的LiveData Quantque Qualquer registro。
可以在房间中使用,在房间中定义类的房间数据库,这是最安全的。

  import android.arch.persistence.room.Database 
import
android.arch.persistence.room.Database
import
android.arch.persistence.room.Database
import
android.arch.persistence.room.Room
import
android.arch.persistence.room.Room
import
android.arch.persistence.room.Room
import
android.arch.persistence.room.RoomDatabase
import
android.arch.persistence.room.RoomDatabase
import
android.arch.persistence.room.RoomDatabase
import
android.content.Context
 @Database(entities = arrayOf(Person:: class ), version = 1) 
abstract
@Database(entities = arrayOf(Person:: class ), version = 1)
abstract
class AppDatabase : RoomDatabase() {
   abstract fun peopleDao(): PeopleDao 
  companion object { 
private
companion object {
private
val DB_NAME = "dbPeople"
private
val DB_NAME = "dbPeople"
private
val DB_NAME = "dbPeople"
private
var INSTANCE: AppDatabase? = null var INSTANCE: AppDatabase? = null
      fun getDatabase(context: Context): AppDatabase? { 
if
fun getDatabase(context: Context): AppDatabase? {
if
(INSTANCE == null ) {
INSTANCE = Room.databaseBuilder(context.applicationContext,
AppDatabase:: class .java,
DB_NAME)
.allowMainThreadQueries()
.build()
}
return
(INSTANCE == null ) {
INSTANCE = Room.databaseBuilder(context.applicationContext,
AppDatabase:: class .java,
DB_NAME)
.allowMainThreadQueries()
.build()
}
return
(INSTANCE == null ) {
INSTANCE = Room.databaseBuilder(context.applicationContext,
AppDatabase:: class .java,
DB_NAME)
.allowMainThreadQueries()
.build()
}
return
INSTANCE
}
}
INSTANCE
}
}
  fun destroyInstance() { 
INSTANCE = null
}
}

Naanotação@ Database informationamos quais entidadesserãopersistidasutilizando a私有财产的“实体”,以及banco。 Perceba que essaéuma classe abstrata,pois assim como nossa interface DAO,一种可实现临时性的实现。
从房间开始到房间的 Room.databaseBuilder从上下文开始,这是对银行的参考。 Perceba que estamos utilizando ométodoallowMainThreadQueries()quenãoérecomendado,pois devemos realizar as consultas em uma thread separada,masnãoestamos fazendo isso aqui para a simpleparamplificéor exemplo。
其他人DAO()retornaráumainstânciadaImplementaçãodo nosso DAO。

DEFININDO操作系统视图模型

Definida nossa camada de acesso ao banco,ViewViews做dosso pequeno projeto。 优先购买权,购买权和使用权的全部责任,由商业担保人在西班牙联邦银行任职。

  import android.app.Application 
import
android.app.Application
import
android.app.Application
import
android.arch.lifecycle.AndroidViewModel
import
android.arch.lifecycle.AndroidViewModel
import
android.arch.lifecycle.AndroidViewModel
import
android.arch.lifecycle.LiveData
  class ListPeopleViewModel(app : Application) : AndroidViewModel(app) { 
var livePeople: LiveData<List>? = null
var db: PeopleDao? = null
ListPeopleViewModel(app : Application) : AndroidViewModel(app) {
var livePeople: LiveData<List>? = null
var db: PeopleDao? = null
   private fun getDao() : PeopleDao? { 
if
fun getDao() : PeopleDao? {
if
fun getDao() : PeopleDao? {
if
(db == null ) {
db = AppDatabase.getDatabase(getApplication())?.peopleDao()
}
return
(db == null ) {
db = AppDatabase.getDatabase(getApplication())?.peopleDao()
}
return
(db == null ) {
db = AppDatabase.getDatabase(getApplication())?.peopleDao()
}
return
db
}
db
}
  fun getPeople(): LiveData<List> { 
if
fun getPeople(): LiveData<List> {
if
(livePeople == null ) {
livePeople = getDao()?.listAll()
}
return
(livePeople == null ) {
livePeople = getDao()?.listAll()
}
return
(livePeople == null ) {
livePeople = getDao()?.listAll()
}
return
livePeople as LiveData<List>
}
}
(livePeople == null ) {
livePeople = getDao()?.listAll()
}
return
livePeople as LiveData<List>
}
}
livePeople as LiveData<List>
}
}

AndroidViewModel类别中创建一个LiveData,然后再添加一个Person类别。 Dessa forma,caso a lista seja nula,carregamos do banco,casocontrárioapenas a retornamos。
法雷莫斯(Faremos uma)类与卡斯特罗(cadastro)相似,而马斯阿佩纳斯(iso apenas)等距或阿索托(ocesso)a banco da nossa UI。

  import android.app.Application 
import
android.app.Application
import
android.app.Application
import
android.arch.lifecycle.AndroidViewModel
  class PersonFormViewModel(app : Application) : AndroidViewModel(app) { 
private
PersonFormViewModel(app : Application) : AndroidViewModel(app) {
private
PersonFormViewModel(app : Application) : AndroidViewModel(app) {
private
var db: PeopleDao? = null
private
var db: PeopleDao? = null
private
var db: PeopleDao? = null
private
fun peopleDao() : PeopleDao? {
if
fun peopleDao() : PeopleDao? {
if
fun peopleDao() : PeopleDao? {
if
(db == null ) {
db = AppDatabase.getDatabase(getApplication())?.peopleDao()
}
return
(db == null ) {
db = AppDatabase.getDatabase(getApplication())?.peopleDao()
}
return
(db == null ) {
db = AppDatabase.getDatabase(getApplication())?.peopleDao()
}
return
db
}
db
}
  fun savePerson(person : Person) { 
if
fun savePerson(person : Person) {
if
(person.id == 0L) {
peopleDao()?.insertPerson(person)
} else
(person.id == 0L) {
peopleDao()?.insertPerson(person)
} else
(person.id == 0L) {
peopleDao()?.insertPerson(person)
} else
{
peopleDao()?.updatePerson(person)
}
}
{
peopleDao()?.updatePerson(person)
}
}
  fun deletePerson(person: Person) { 
peopleDao()?.deletePerson(person)
}
}

o savePerson(Person)的插入对象或对象的标识为“ 0”或“ 0”。 JáométododeletePerson(人)excluiráo objeto人。

君丹多·图多

Finalmente vamos的实现者是telas daaplicação,começandopela tela de listagem。

  import android.arch.lifecycle.LifecycleRegistry 
import
android.arch.lifecycle.LifecycleRegistry
import
android.arch.lifecycle.LifecycleRegistry
import
android.arch.lifecycle.LifecycleRegistryOwner
import
android.arch.lifecycle.LifecycleRegistryOwner
import
android.arch.lifecycle.LifecycleRegistryOwner
import
android.arch.lifecycle.Observer
import
android.arch.lifecycle.Observer
import
android.arch.lifecycle.Observer
import
android.arch.lifecycle.ViewModelProviders
import
android.arch.lifecycle.ViewModelProviders
import
android.arch.lifecycle.ViewModelProviders
import
android.os.Bundle
import
android.os.Bundle
import
android.os.Bundle
import
android.support.v7.app.AppCompatActivity
import
android.support.v7.app.AppCompatActivity
import
android.support.v7.app.AppCompatActivity
import
android.widget.ArrayAdapter
import
android.widget.ArrayAdapter
import
android.widget.ArrayAdapter
import
kotlinx.android.synthetic.main.activity_list_people.*
  class ListPeopleActivity : AppCompatActivity(), LifecycleRegistryOwner { 

var lifecycleRegistry = LifecycleRegistry( this )
ListPeopleActivity : AppCompatActivity(), LifecycleRegistryOwner {

var lifecycleRegistry = LifecycleRegistry( this )
  override fun getLifecycle(): LifecycleRegistry = lifecycleRegistry 
  override fun onCreate(savedInstanceState: Bundle?) { 
super .onCreate(savedInstanceState)
setContentView(R.layout.activity_list_people)
fab.setOnClickListener {
PersonFormFragment().show(supportFragmentManager, "form")
}
  val model = ViewModelProviders.of( this ) 
.get(ListPeopleViewModel:: class .java)
  model.getPeople().observe( this , Observer { people -> 
listview.adapter = ArrayAdapter(
this @ListPeopleActivity,
android.R.layout.simple_list_item_1,
people)
listview.setOnItemClickListener { _, _, position, _ ->
val person = people?.get(position)
if
model.getPeople().observe( this , Observer { people ->
listview.adapter = ArrayAdapter(
this @ListPeopleActivity,
android.R.layout.simple_list_item_1,
people)
listview.setOnItemClickListener { _, _, position, _ ->
val person = people?.get(position)
if
(person != null ) {
PersonFormFragment.newInstance(person)
.show(supportFragmentManager, "form")
}
}
})
}
(person != null ) {
PersonFormFragment.newInstance(person)
.show(supportFragmentManager, "form")
}
}
})
}
  override fun onDestroy() { 
AppDatabase.destroyInstance()
super .onDestroy()
}
}

实现LifecycleRegistryOwner的 No类的AppCompatActivity类。 Essa接口要求的实现方法getLifecycle()和对象的生命周期注册表。 Poderíamossimplesmente Herdade de LifecycleActivity ,mass classe herda de FragmentActivity,enterãopersíamos和ActionBarPadrãoqueéédicionada。

多数布局或活动布局,列表列表com List @ com ID @ + id / listview uma FloatingActionButton com id @ + id / fab。 使用简单的用户界面或组件的Perceba que estamos组件。 Isoéfeitograçasao kotlinx(科特林扩展)。

没有FAB,没有PersonFormFragment(que mostraremos a seguir)éexibido。 在视图模型上进行分类的类在视图模型提供者之间进行分类。
在ViewModel中, 观察到比索马斯清单和原始清单, 观察 sabermos quando,然后观察清单。 Nesse caso,定义适配器的名称或列表列表,甚至没有单击任何项​​目。 Perceba que comonãoestamos utilizando todos osparâmetros,estamos utilizando o“ _” no lugar dospectivos nomes。

一个cadastro类的DialogFragment类。

  import android.arch.lifecycle.ViewModelProviders 
import
android.arch.lifecycle.ViewModelProviders
import
android.arch.lifecycle.ViewModelProviders
import
android.content.Context
import
android.content.Context
import
android.content.Context
import
android.os.Bundle
import
android.os.Bundle
import
android.os.Bundle
import
android.support.v4.app.DialogFragment
import
android.support.v4.app.DialogFragment
import
android.support.v4.app.DialogFragment
import
android.view.LayoutInflater
import
android.view.LayoutInflater
import
android.view.LayoutInflater
import
android.view.View
import
android.view.View
import
android.view.View
import
android.view.ViewGroup
import
android.view.ViewGroup
import
android.view.ViewGroup
import
kotlinx.android.synthetic.main.fragment_person_form.*
kotlinx.android.synthetic.main.fragment_person_form.*

class PersonFormFragment : DialogFragment() {
lateinit var person : Person
lateinit var viewModel : PersonFormViewModel
PersonFormFragment : DialogFragment() {
lateinit var person : Person
lateinit var viewModel : PersonFormViewModel
  override fun onAttach(context: Context?) { 
super .onAttach(context)
viewModel = ViewModelProviders.of( this )
.get(PersonFormViewModel:: class .java)
  person = arguments?.getSerializable(EXTRA_PERSON) 
as? Person ?: Person()
}
  override fun onCreateView(inflater: LayoutInflater?, 
container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return
override fun onCreateView(inflater: LayoutInflater?,
container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return
inflater?.inflate(R.layout.fragment_person_form,
container, false )
}
inflater?.inflate(R.layout.fragment_person_form,
container, false )
}
  override fun onViewCreated(view: View?, 
savedInstanceState: Bundle?) {
super .onViewCreated(view, savedInstanceState)
edtFirstName.setText(person.firstName)
edtLastName.setText(person.lastName)
edtAge.setText( if
override fun onViewCreated(view: View?,
savedInstanceState: Bundle?) {
super .onViewCreated(view, savedInstanceState)
edtFirstName.setText(person.firstName)
edtLastName.setText(person.lastName)
edtAge.setText( if
(person.age != 0 override fun onViewCreated(view: View?,
savedInstanceState: Bundle?) {
super .onViewCreated(view, savedInstanceState)
edtFirstName.setText(person.firstName)
edtLastName.setText(person.lastName)
edtAge.setText( if
(person.age != 0 || person.id != 0L)
person.age.toString() else
|| person.id != 0L)
person.age.toString() else
|| person.id != 0L)
person.age.toString() else
"")
btnRemove.visibility = if
"")
btnRemove.visibility = if
"")
btnRemove.visibility = if
(person.id == 0L) View.GONE
else
(person.id == 0L) View.GONE
else
(person.id == 0L) View.GONE
else
View.VISIBLE
btnCancel.setOnClickListener { dismiss() }
btnSave.setOnClickListener { savePerson() }
btnRemove.setOnClickListener { removePerson() }
}
View.VISIBLE
btnCancel.setOnClickListener { dismiss() }
btnSave.setOnClickListener { savePerson() }
btnRemove.setOnClickListener { removePerson() }
}
   private fun removePerson() { 
viewModel.deletePerson(person)
dismiss()
}
fun removePerson() {
viewModel.deletePerson(person)
dismiss()
}
   private fun savePerson() { 
person.firstName = edtFirstName.text.toString()
person.lastName = edtLastName.text.toString()
person.age = edtAge.text.toString().toInt()
viewModel.savePerson(person)
dismiss()
}
fun savePerson() {
person.firstName = edtFirstName.text.toString()
person.lastName = edtLastName.text.toString()
person.age = edtAge.text.toString().toInt()
viewModel.savePerson(person)
dismiss()
}
  companion object { 
val EXTRA_PERSON = "person"
  fun newInstance(person: Person) : PersonFormFragment { 
val args = Bundle()
args.putSerializable(EXTRA_PERSON, person)
val f = PersonFormFragment()
f.arguments = args
return
fun newInstance(person: Person) : PersonFormFragment {
val args = Bundle()
args.putSerializable(EXTRA_PERSON, person)
val f = PersonFormFragment()
f.arguments = args
return
f
}
}
}
f
}
}
}

编辑布局(edittName(edtFirstName,edtLastName e edtAge)类别的人员,注释(btnSave,btnRemove,saltar,取消或取消) 。 发送给您或发送电子邮件给其他用户。
否在视图上附加附加的ViewModel和对象。 Cramos um Novo的Senãotivermos passado esse objeto。 Perceba que nessainstruçãoestamos usando“?”否,自变量,pois ele pode ser null,否“ as?”,否,人员(isso se chama save cast)从porutil utilizamos o“ elvis operator” ,从前到后再进行注射。
Non de especial no onCreateView,mast onCreateCreated注释inestruçãointerestante paraqueménovo em Kotlinqueééif / else retornando um valor(Java的“ seria o mesmo que oternário”)。
不可以删除人员,也不能删除ViewModel对象或保存对象。 由fim提出的“工厂方法”是“新方法”。

塞弗尔的结果是:

不能将Google IO de 2017 utilizando Kotlin用作参考书目。 Obviamente存在于一个探索者中,在esprimo que esse jas ajude a dar osprimiros passos com essas API中。

Para saber mais,Assistam essesvídeosdo Google IO ea adocumentaçãodessas libs。 😉

体系结构组件—简介
https://www.youtube.com/watch?v=FrteWKKVyzI

体系结构组件—解决生命周期问题
https://www.youtube.com/watch?v=bEKNi1JOrNs

体系结构组件—持久性和脱机
https://www.youtube.com/watch?v=MfHsPGQ6bgE

官方文件
https://developer.android.com/topic/libraries/architecture/index.html

4br4ç05,
恩劳伯