经常在做状态刷新的工作同事,最常使用一些EventBus ,或者RxAndroid来刷新页面.有时候在刷新页面时,有些繁琐。我所做的这个,是一个新的发现,通过属性来改页面的状态,感觉有点想Reat-Native。prop 所说的状态机有点类似。
实验操作如下:
1.创建一个实体类,创建一个activity.,一个接口
1)接口
EntityListener.kt
interface EntityListener {
fun afterChange(oldValue: Any, newValue: Any)
}
2)
BaseEntity.kt
package com.example.chenkui.myapplication.entity
import com.example.chenkui.myapplication.lister.EntityListener
open class BaseEntity {
var entityListener: EntityListener? = null
/**
* 这个在属性值改变之后的监听回调,
* 这里是新旧值的监听回调
*/
inline fun onChange(crossinline onChange: (oldValue: Any, newValue: Any) -> Unit) {
this.entityListener = object : EntityListener {
override fun afterChange(oldValue: Any, newValue: Any) = onChange(oldValue, newValue)
}
}
/**
* 这个在属性值改变之后的监听回调,
* 属性值的改变的回调
*/
internal fun onChangeCall(onChange: () -> Unit) {
this.entityListener = object : EntityListener {
override fun afterChange(oldValue: Any, newValue: Any) = onChange()
}
}
/**
* 这个在实体类继承 属性监听调用
* var obserableProp: String by Delegates.observable("默认值") { prop, old, new ->
* call(old, new)
* }
*
*/
internal fun call(oldValue: Any, newValue: Any) {
if (entityListener != null) {
entityListener!!.afterChange(oldValue, newValue)
}
}
}
3)
TestEntity.kt
package com.example.chenkui.myapplication.entity;
import kotlin.properties.Delegates
class TestEntity : BaseEntity() {
companion object {
var testEntity = TestEntity()
}
/**
* 属性监听
* //prop lambda 表达式的一个参数代表被监听的属性
* //old 第二个参数代表修改之前的值
* //new 第三个参数代表被设置的新值
*/
var obserableProp: String by Delegates.observable("默认值") { prop, old, new ->
call(old, new)
println("===$prop==的====$old==被改为==$new==")
}
var vetoableProp: Int by Delegates.vetoable(20) {
prop, old, new ->
call(old, new)
println("===$prop==的====$old==被改为==$new==")
new > old
}
}
4) MainActivity.kt
var testEntity = TestEntity.testEntity
public fun observable(v: View) {
testEntity.onChangeCall {
(v as TextView).text = testEntity.obserableProp
}
testEntity.obserableProp = "hello"
}
public fun observable1(v: View) {
Toast.makeText(this, "test", Toast.LENGTH_LONG).show()
testEntity.obserableProp = "修改一次"
}
执行observable(v:View) | 执行observable1(v:View) |
---|---|
初始值显示 "默认值"改变成"hello" | 初始值"hello"改变成 “修改一次” |
经过测试,发信可以在一个activity,刷新另一个activity ,
比如 在创建一个新activity ,执行下面这个代码,就可以刷新上个页面的TextView
TestEntity.testEntity.obserableProp = "Main2Activity"
至于跨进程发面还有试过,有待探究。