类委托
类委托有点类似于java中的代理模式
interface base{ fun text() } //被委托的类(真实的类) class baseimpl(val x:string): base { override fun text() { println(x) } } //委托类 class devices(b:base):base by b fun main(){ var b = baseimpl("真实的类") devices(b).text() }
输出
委托类(代理类)持有真实类的对象,然后委托类(代理类)调用真实类的同名方法,最终真正实现的是方法的是真实类,这其实就是代理模式
kotlin中的委托借助于by关键字,by关键字后面就是被委托类
反编译成java代码
public final class baseimpl implements base { @notnull private final string x; public baseimpl(@notnull string x) { intrinsics.checknotnullparameter(x, "x"); super(); this.x = x; } @notnull public final string getx() { return this.x; } public void text() { string var1 = this.x; system.out.println(var1); } } // devices.java package com.example.memoryoptimizing.delegate; import kotlin.metadata; import kotlin.jvm.internal.intrinsics; import org.jetbrains.annotations.notnull; @metadata( mv = {1, 9, 0}, k = 1, xi = 48, d1 = {"\u0000\u0012\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0002\b\u0003\n\u0002\u0010\u0002\n\u0000\u0018\u00002\u00020\u0001b\r\u0012\u0006\u0010\u0002\u001a\u00020\u0001¢\u0006\u0002\u0010\u0003j\t\u0010\u0004\u001a\u00020\u0005h\u0096\u0001¨\u0006\u0006"}, d2 = {"lcom/example/memoryoptimizing/delegate/devices;", "lcom/example/memoryoptimizing/delegate/base;", "b", "(lcom/example/memoryoptimizing/delegate/base;)v", "text", "", "app_debug"} ) public final class devices implements base { // $ff: synthetic field private final base $$delegate_0; public devices(@notnull base b) { intrinsics.checknotnullparameter(b, "b"); super(); this.$$delegate_0 = b; } public void text() { this.$$delegate_0.text(); } } // baseimplkt.java package com.example.memoryoptimizing.delegate; import kotlin.metadata; @metadata( mv = {1, 9, 0}, k = 2, xi = 48, d1 = {"\u0000\b\n\u0000\n\u0002\u0010\u0002\n\u0000\u001a\u0006\u0010\u0000\u001a\u00020\u0001¨\u0006\u0002"}, d2 = {"main", "", "app_debug"} ) public final class baseimplkt { public static final void main() { baseimpl b = new baseimpl("真实的类"); (new devices((base)b)).text(); } // $ff: synthetic method public static void main(string[] args) { main(); } }
可以看到,devices持有baseimpl对象,重写text方法,text方法内部调用的是baseimpl.text()
属性委托
属性委托和类委托一样,属性委托其实是对属性的set/get方法的委托,把set/get方法委托给setvalue/getvalue方法,因此被委托类(真实类)需要提供setvalue/getvalue方法,val属性只需要提供setvalue方法
属性委托语法:
val/var <属性名>:<类型> by <表达式>
class b{ //委托属性 var a : string by text() } class text { operator fun getvalue(thisref: any?, property: kproperty<*>): string { return "属性拥有者 = $thisref ,属性的名字 = ‘${property.name}' 属性的值" } operator fun setvalue(thisref: any?, property: kproperty<*>, value: string) { println("属性的值 = $value 属性的名字 = '${property.name}' 属性拥有者 = $thisref") } } fun main(){ var b = b() println(b.a) b.a = "ahaha" }
输出
属性a委托给了text,而且text类中有setvalue和getvalue,所有当我们调用属性a的set/get方法时候,会委托到text的setvalue/getvalue。
thisref:属性的拥有者
property:对属性的描述,是kproperty<*>类型或者父类
value:属性的值
反编译成java代码
public final class b { // $ff: synthetic field static final kproperty[] $$delegatedproperties; @notnull private final text a$delegate = new text(); @notnull public final string geta() { return this.a$delegate.getvalue(this, $$delegatedproperties[0]); } public final void seta(@notnull string var1) { intrinsics.checknotnullparameter(var1, "<set-?>"); this.a$delegate.setvalue(this, $$delegatedproperties[0], var1); } static { kproperty[] var0 = new kproperty[]{reflection.mutableproperty1((mutablepropertyreference1)(new mutablepropertyreference1impl(b.class, "a", "geta()ljava/lang/string;", 0)))}; $$delegatedproperties = var0; } } // text.java package com.example.memoryoptimizing.delegate; import kotlin.metadata; import kotlin.jvm.internal.intrinsics; import kotlin.reflect.kproperty; import org.jetbrains.annotations.notnull; import org.jetbrains.annotations.nullable; @metadata( mv = {1, 9, 0}, k = 1, xi = 48, d1 = {"\u0000\"\n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0002\b\u0002\n\u0002\u0010\u000e\n\u0002\b\u0002\n\u0002\u0018\u0002\n\u0000\n\u0002\u0010\u0002\n\u0002\b\u0002\u0018\u00002\u00020\u0001b\u0005¢\u0006\u0002\u0010\u0002j\u001f\u0010\u0003\u001a\u00020\u00042\b\u0010\u0005\u001a\u0004\u0018\u00010\u00012\n\u0010\u0006\u001a\u0006\u0012\u0002\b\u00030\u0007h\u0086\u0002j'\u0010\b\u001a\u00020\t2\b\u0010\u0005\u001a\u0004\u0018\u00010\u00012\n\u0010\u0006\u001a\u0006\u0012\u0002\b\u00030\u00072\u0006\u0010\n\u001a\u00020\u0004h\u0086\u0002¨\u0006\u000b"}, d2 = {"lcom/example/memoryoptimizing/delegate/text;", "", "()v", "getvalue", "", "thisref", "property", "lkotlin/reflect/kproperty;", "setvalue", "", "value", "app_debug"} ) public final class text { @notnull public final string getvalue(@nullable object thisref, @notnull kproperty property) { intrinsics.checknotnullparameter(property, "property"); return "属性拥有者 = " + thisref + " ,属性的名字 = ‘" + property.getname() + "' 属性的值"; } public final void setvalue(@nullable object thisref, @notnull kproperty property, @notnull string value) { intrinsics.checknotnullparameter(property, "property"); intrinsics.checknotnullparameter(value, "value"); string var4 = "属性的值 = " + value + " 属性的名字 = '" + property.getname() + "' 属性拥有者 = " + thisref; system.out.println(var4); } } // textkt.java package com.example.memoryoptimizing.delegate; import kotlin.metadata; @metadata( mv = {1, 9, 0}, k = 2, xi = 48, d1 = {"\u0000\b\n\u0000\n\u0002\u0010\u0002\n\u0000\u001a\u0006\u0010\u0000\u001a\u00020\u0001¨\u0006\u0002"}, d2 = {"main", "", "app_debug"} ) public final class textkt { public static final void main() { b b = new b(); string var1 = b.geta(); system.out.println(var1); b.seta("ahaha"); } // $ff: synthetic method public static void main(string[] args) { main(); } }
可以看到b类持有text对象,当调用b.get()方法,内部调用了text.getvalue(),b中创建了kproperty来保存属性的各种参数。
简单的实现属性委托
每次实现委托都要写getvalue/setvalue方法,相对来说比较麻烦,kotlin也提供了接口,方便我们重写这些方法,readonlyproperty和readwriterproperty
public fun interface readonlyproperty<in t, out v> { /** * returns the value of the property for the given object. * @param thisref the object for which the value is requested. * @param property the metadata for the property. * @return the property value. */ public operator fun getvalue(thisref: t, property: kproperty<*>): v } /** * base interface that can be used for implementing property delegates of read-write properties. * * this is provided only for convenience; you don't have to extend this interface * as long as your property delegate has methods with the same signatures. * * @param t the type of object which owns the delegated property. * @param v the type of the property value. */ public interface readwriteproperty<in t, v> : readonlyproperty<t, v> { /** * returns the value of the property for the given object. * @param thisref the object for which the value is requested. * @param property the metadata for the property. * @return the property value. */ public override operator fun getvalue(thisref: t, property: kproperty<*>): v /** * sets the value of the property for the given object. * @param thisref the object for which the value is requested. * @param property the metadata for the property. * @param value the value to set. */ public operator fun setvalue(thisref: t, property: kproperty<*>, value: v) }
被委托类只需要实现接口重写方法就行,val继承readonlyproperty
class text1:readonlyproperty<any,string>{ override fun getvalue(thisref: any, property: kproperty<*>): string { return "属性拥有者 = $thisref ,属性的名字 = ‘${property.name}' 属性的值" } } class text2: readwriteproperty<any,string>{ override fun getvalue(thisref: any, property: kproperty<*>): string { return "属性拥有者 = $thisref ,属性的名字 = ‘${property.name}' 属性的值" } override fun setvalue(thisref: any, property: kproperty<*>, value: string) { println("属性的值 = $value 属性的名字 = '${property.name}' 属性拥有者 = $thisref") } }
class b{ val b :string by text1() var c : string by text2() }
fun main(){ var b = b() b.c = "1" }
kotlin标准库中提供的几个委托
- 延迟属性(lazy properties):其值只在访问时计算
- 可观察属性(observable properties):监听器会收到此属性的变更通知
- 把多个属性映射到map中,而不存在单个字段
延迟属性lazy
lazy()接收一个lambda,返回lazy实例,返回的实例可以作为实现延迟属性的委托,仅在第一次调用属性进行初始化
class lazy{ val name:string by lazy(lazythreadsafetymode.synchronized){ println("第一次初始化") "aa" } } fun main(){ var lazy = lazy() println(lazy.name) println(lazy.name) }
反编译java代码
public final class lazy { @notnull private final kotlin.lazy name$delegate; public lazy() { this.name$delegate = kotlin.lazykt.lazy( (function0)null.instance); } @notnull public final string getname() { kotlin.lazy var1 = this.name$delegate; object var2 = null; return (string)var1.getvalue(); } } // lazykt.java package com.example.memoryoptimizing.delegate; import kotlin.metadata; @metadata( mv = {1, 9, 0}, k = 2, xi = 48, d1 = {"\u0000\b\n\u0000\n\u0002\u0010\u0002\n\u0000\u001a\u0006\u0010\u0000\u001a\u00020\u0001¨\u0006\u0002"}, d2 = {"main", "", "app_debug"} ) public final class lazykt { public static final void main() { lazy lazy = new lazy(); string var1 = lazy.getname(); system.out.println(var1); var1 = lazy.getname(); system.out.println(var1); } // $ff: synthetic method public static void main(string[] args) { main(); } }
发现lazy再初始化时生成了name $ delegate,变量是kotlin.lazy类型的,而getname()方法返回的其实就是name $ delegate.getvalue()
name $ delegate是由kotlin.lazykt.lazy (function0)null.instance);生成的,可以看一下源码
public actual fun <t> lazy(initializer: () -> t): lazy<t> = synchronizedlazyimpl(initializer)
最终是由synchronizedlazyimpl生成
private class synchronizedlazyimpl<out t>(initializer: () -> t, lock: any? = null) : lazy<t>, serializable { private var initializer: (() -> t)? = initializer @volatile private var _value: any? = uninitialized_value // final field is required to enable safe publication of constructed instance private val lock = lock ?: this override val value: t get() { val _v1 = _value if (_v1 !== uninitialized_value) { @suppress("unchecked_cast") return _v1 as t } return synchronized(lock) { val _v2 = _value if (_v2 !== uninitialized_value) { @suppress("unchecked_cast") (_v2 as t) } else { val typedvalue = initializer!!() _value = typedvalue initializer = null typedvalue } } } override fun isinitialized(): boolean = _value !== uninitialized_value override fun tostring(): string = if (isinitialized()) value.tostring() else "lazy value not initialized yet." private fun writereplace(): any = initializedlazyimpl(value) }
可以直接看value的get方法,如果_v1 !== uninitialized_value则表明已经初始化过了,就直接返回value,否则表明没有初始化过,调用initializer方法,也就是lazy的lambda表达式
lazy委托参数
public enum class lazythreadsafetymode { /** * locks are used to ensure that only a single thread can initialize the [lazy] instance. */ synchronized, /** * initializer function can be called several times on concurrent access to uninitialized [lazy] instance value, * but only the first returned value will be used as the value of [lazy] instance. */ publication, /** * no locks are used to synchronize an access to the [lazy] instance value; if the instance is accessed from multiple threads, its behavior is undefined. * * this mode should not be used unless the [lazy] instance is guaranteed never to be initialized from more than one thread. */ none, }
- synchronized:添加同步锁,使lazy延迟初始化线程安全
- publication:初始化的lambda表达式,可以在同一时间多次调用,但是只有第一次的返回值作为初始化值
- none:没有同步锁,非线程安全
使用
val name :string by lazy(lazythreadsafetymode.synchronized) { println("第一次调用初始化") "aa" } }
可观察属性observable委托
可以观察一个属性的变化过程
class observable { var a:string by delegates.observable("默认值"){ property, oldvalue, newvalue -> println("${oldvalue} -> ${newvalue}") } } fun main(){ var observable = observable() observable.a = "第一次修改的值" observable.a = "第二次修改的值" }
vetoable委托
vetoable和observable一样,可以观察属性的变化,不同的是vetoable可以决定是否使用新值
class vetoable { var age:int by delegates.vetoable(0){ property, oldvalue, newvalue -> println("oldvalue = $oldvalue -> oldvalue = $newvalue" ) newvalue > oldvalue } } fun main() { var c = vetoable() c.age = 5 println(c.age) c.age = 10 println(c.age) c.age = 8 println(c.age) c.age = 20 println(c.age) }
可以看到,当新值小于旧值,就会不生效
属性储存在map中
class d(val map:map<string,any?>){ val name:string by map val age:int by map } fun main() { var d = d( mapof( "name" to "小明", "age" to 12 ) ) println("name = ${d.name},age = ${d.age}") }
实践方式
双击back退出
private var backpressedtime by delegates.observable(0l){pre,old,new -> //2次的时间间隔小于2秒就退出了 if(new - old < 2000){ finish() }else{ toast.maketext(this,"再按返回键退出",toast.length_long) } } override fun onbackpressed() { super.onbackpressed() backpressedtime = system.currenttimemillis() }
fragment/activity传参
在项目中经常需要给fragment/activity传递参数
模版代码
private const val arg_param1 = "param1" private const val arg_param2 = "param2" class delegatefragment : fragment() { // todo: rename and change types of parameters private var param1: string? = null private var param2: string? = null override fun oncreate(savedinstancestate: bundle?) { super.oncreate(savedinstancestate) arguments?.let { param1 = it.getstring(arg_param1) param2 = it.getstring(arg_param2) } } override fun oncreateview( inflater: layoutinflater, container: viewgroup?, savedinstancestate: bundle? ): view? { // inflate the layout for this fragment return inflater.inflate(r.layout.fragment_delegate, container, false) } companion object { /** * use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 parameter 1. * @param param2 parameter 2. * @return a new instance of fragment delegatefragment. */ // todo: rename and change types and number of parameters @jvmstatic fun newinstance(param1: string, param2: string) = delegatefragment().apply { arguments = bundle().apply { putstring(arg_param1, param1) putstring(arg_param2, param2) } } } }
我们可以把参数赋值和获取的代码抽取委托类,然后把param1和param2声明为委托属性
修改后的fragment代码
class delegatefragment : fragment() { private var param1: string? by argumentnullable() private var param2: string by argument("1") override fun oncreate(savedinstancestate: bundle?) { super.oncreate(savedinstancestate) log.d("delegatefragment","param1 ${param1} param2 ${param2}") } override fun oncreateview( inflater: layoutinflater, container: viewgroup?, savedinstancestate: bundle? ): view? { // inflate the layout for this fragment return inflater.inflate(r.layout.fragment_delegate, container, false) } companion object { /** * use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 parameter 1. * @param param2 parameter 2. * @return a new instance of fragment delegatefragment. */ // todo: rename and change types and number of parameters @jvmstatic fun newinstance(param1: string, param2: string) = delegatefragment().apply { this.param1 = param1 this.param2 = param2 } } }
委托类
import android.os.bundle import android.os.parcelable import android.util.log import androidx.fragment.app.fragment import java.io.serializable import kotlin.properties.readwriteproperty import kotlin.reflect.kproperty fun <t> fragment.argumentnullable() = fragmentargumentpropertynullable<t>() fun <t> fragment.argument(defaultvalue:t? = null) = fragmentargumentproperty<t>(defaultvalue) class fragmentargumentpropertynullable<t> : readwriteproperty<fragment,t?>{ override fun getvalue(thisref: fragment, property: kproperty<*>): t? { return thisref.arguments?.getvalue(property.name) } override fun setvalue(thisref: fragment, property: kproperty<*>, value: t?) { log.d("delegatefragment","property.name ${property.name} thisref.arguments ${thisref.arguments}") val arguments = thisref.arguments?:bundle().also { thisref.arguments = it } if(arguments.containskey(property.name)){ return } arguments[property.name] = value } } class fragmentargumentproperty<t> (private val defaultvalue: t? = null): readwriteproperty<fragment,t>{ override fun getvalue(thisref: fragment, property: kproperty<*>): t { return thisref.arguments?.getvalue(property.name) as? t ?:defaultvalue ?:throw illegalstateexception("property ${property.name} could not be read") } override fun setvalue(thisref: fragment, property: kproperty<*>, value: t) { val arguments = thisref.arguments?:bundle().also { thisref.arguments = it } if(arguments.containskey(property.name)){ return } arguments[property.name] = value } } fun <t> bundle.getvalue(key:string):t?{ return get(key) as t? } //操作符重载a[i] = b set() a.set(i, b) operator fun <t> bundle.set(key: string, value: t?) { when (value) { is boolean -> putboolean(key, value) is byte -> putbyte(key, value) is char -> putchar(key, value) is short -> putshort(key, value) is int -> putint(key, value) is long -> putlong(key, value) is float -> putfloat(key, value) is double -> putdouble(key, value) is string? -> putstring(key, value) is charsequence? -> putcharsequence(key, value) is serializable? -> putserializable(key, value) // also arraylist is parcelable? -> putparcelable(key, value) is bundle? -> putbundle(key, value) is booleanarray? -> putbooleanarray(key, value) is bytearray? -> putbytearray(key, value) is chararray? -> putchararray(key, value) is shortarray? -> putshortarray(key, value) is intarray? -> putintarray(key, value) is longarray? -> putlongarray(key, value) is floatarray? -> putfloatarray(key, value) is doublearray? -> putdoublearray(key, value) is arraylist<*>? -> throw illegalstateexception("arraylist<*> $key is not supported") is array<*>? -> throw illegalstateexception("array<*> $key is not supported") else -> throw illegalstateexception("type $key is not supported") } }
相比于常规的写法,使用属性委托优势会相对明显,不需要定义key字符串,而是使用变量名作为key。不再需要编写向argument设置参数和读取参数的代码,声明可空参数时也可以声明默认值。
viewbinding和委托
在fragment中使用
class delegatefragment : fragment(r.layout.fragment_delegate) { private var _binding: fragmentdelegatebinding? = null private val binding get() = _binding!! override fun onviewcreated(view: view, savedinstancestate: bundle?) { super.onviewcreated(view, savedinstancestate) _binding = fragmentdelegatebinding.bind(view) binding.tvname.text = "this is hello world" } override fun ondestroyview() { super.ondestroyview() //置空,防止内存泄漏 _binding = null } }
viewbinding绑定类的源码,反编译如下:
public final class fragmentdelegatebinding implements viewbinding { private final constraintlayout rootview; public final textview tvdisplay; private fragmentdelegatebinding(constraintlayout paramconstraintlayout1, textview paramtextview) this.rootview = paramconstraintlayout1; this.tvdisplay = paramtextview; } public static fragmentdelegatebindingbind(view paramview) { textview localtextview = (textview)paramview.findviewbyid(2131165363); if (localtextview != null) { return new activitymainbinding((constraintlayout)paramview, localtextview); }else { paramview = "tvdisplay"; } throw new nullpointerexception("missing required view with id: ".concat(paramview)); } public static fragmentdelegatebinding inflate(layoutinflater paramlayoutinflater) { return inflate(paramlayoutinflater, null, false); } public static fragmentdelegatebinding inflate(layoutinflater paramlayoutinflater, viewgroup paramviewgroup, boolean paramboolean) { paramlayoutinflater = paramlayoutinflater.inflate(2131361821, paramviewgroup, false); if (paramboolean) { paramviewgroup.addview(paramlayoutinflater); } return bind(paramlayoutinflater); } public constraintlayout getroot() { return this.rootview; } }
通过委托的方式进行优化
- 委托viewbinding.bind()的调用 -> 反射
- 委托destroy时binding = null的调用 -> 监听fragment视图生命周期
- 想要binding属性声明为非空不可变变量val -> 属性委托readonlyproperty<f,v>
编写委托类,详细内容可看注释
package com.example.memoryoptimizing.delegate import android.os.handler import android.os.looper import android.util.log import android.view.view import androidx.fragment.app.fragment import androidx.lifecycle.lifecycle import androidx.lifecycle.lifecycleobserver import androidx.lifecycle.lifecycleowner import androidx.viewbinding.viewbinding import kotlin.properties.readonlyproperty import kotlin.reflect.kproperty //为什么使用inline fun<reified v>,方便直接拿到v::class.java /** * fun <v> printclass() { * println(v::class.java) // ❌ 编译错误:cannot access 'java.lang.class' for a type parameter v * } * inline fun <reified v> printclass() { * println(v::class.java) // ✅ 输出如:class kotlin.string * } */ //在属性委托中,编译器可以通过属性声明的类型,如 fragmentdelegatebinding)来推断泛型函数中的具体类型参数; // 而在普通函数调用中,仅凭返回值或赋值目标无法反推出泛型参数的具体类型。 /** ✅ 场景一:属性委托 + reified 泛型函数 ✅ 可以推断 private val binding: fragmentdelegatebinding by viewbindingv1() ❌ 场景二:普通函数调用 ❌ 无法推断 inline fun <reified v> gettypename(): string { return v::class.java.name } val name: string = gettypename() */ private const val tag = "viewbindingproperty" //使用inline fun <reified v>可以在调用泛型函数时省略参数的传递,kotlin会自动根据泛型类型帮你找到对应的class<t> public inline fun <reified v:viewbinding> viewbindingv1() = viewbindingv1(v::class.java) public inline fun <reified t:viewbinding> viewbindingv1(clazz:class<t>):fragmentviewbindingproperttv1<fragment,t>{ val bindmethod = clazz.getmethod("bind", view::class.java) return fragmentviewbindingproperttv1{ fragment-> /** * 调用静态方法bind(view view),第一个参数为null(因为是静态方法) 第二个参数是view,来自fragment的requireview() * as t 将结果强制转换为泛型t,即具体的viewbinding子类(如fragmentdelegatebinding) * fragmentdelegatebinding.bind(fragment.requireview()) */ bindmethod.invoke(null,fragment.requireview()) as t } } /** * viewbinder 创建绑定类对象 */ class fragmentviewbindingproperttv1<in f:fragment,out v: viewbinding>( private val viewbinder:(f) ->v //给定一个 fragment(或其子类),返回一个对应的 viewbinding 实例 ):readonlyproperty<f,v>{ private var viewbinding:v? = null override fun getvalue(thisref: f, property: kproperty<*>): v { //viewbinding不为空说明已经绑定,直接返回 viewbinding?.let { return it } //fragment视图的生命周期 val lifecycle = thisref.viewlifecycleowner.lifecycle //实例化绑定类对象 val viewbinding = viewbinder(thisref) if(lifecycle.currentstate == lifecycle.state.destroyed){ log.w( tag, "access to viewbinding after lifecycle is destroyed or hasn't created yet. " + "the instance of viewbinding will be not cached." ) }else{ lifecycle.addobserver(clearondestroylifecycleobserver()) this.viewbinding = viewbinding } return viewbinding } fun clear(){ viewbinding = null } private inner class clearondestroylifecycleobserver : lifecycleobserver{ private val mainhandler = handler(looper.getmainlooper()) fun ondestroy(owner:lifecycleowner){ owner.lifecycle.removeobserver(this) mainhandler.post { clear() } } } }
使用例子:
class delegatefragment : fragment(r.layout.fragment_delegate) { private val binding : fragmentdelegatebinding by viewbindingv1() override fun onviewcreated(view: view, savedinstancestate: bundle?) { super.onviewcreated(view, savedinstancestate) binding.tvname.text = "this is hello world" } }
不使用反射的方式,反射调用bind函数的主要目的是获得一个viewbinding绑定类对象,我们可以把创建对象的行为交给外部去定义
inline fun <f:fragment,v:viewbinding> viewbindingv2( crossinline viewbinder:(view) -> v,//接受一个view,返回binding实例 crossinline viewprovider:(f) -> view = { fragment -> fragment.requireview() //这里的fragment就是f } //接受一个fragment,返回它的view ) = fragmentviewbindingpropertyv2{ fragment:f -> viewbinder(viewprovider(fragment)) //fragmentdelegatebinding.bind(fragment.requireview()) }//fragment它是 kotlin 属性委托机制在访问 binding 属性时自动传入的当前 fragment 实例 class fragmentviewbindingpropertyv2<in f:fragment , out v: viewbinding>( private val viewbinder:(f) -> v ):readonlyproperty<f,v>{ private var viewbinding: v? = null override fun getvalue(thisref: f, property: kproperty<*>): v { //viewbinding不为空说明已经绑定,直接返回 viewbinding?.let { return it } //fragment视图的生命周期 val lifecycle = thisref.viewlifecycleowner.lifecycle //实例化绑定类对象 val viewbinding = viewbinder(thisref) if (lifecycle.currentstate == lifecycle.state.destroyed) { log.w( tag, "access to viewbinding after lifecycle is destroyed or hasn't created yet. " + "the instance of viewbinding will be not cached." ) } else { lifecycle.addobserver(clearondestroylifecycleobserver()) this.viewbinding = viewbinding } return viewbinding } fun clear() { viewbinding = null } private inner class clearondestroylifecycleobserver : lifecycleobserver { private val mainhandler = handler(looper.getmainlooper()) fun ondestroy(owner: lifecycleowner) { owner.lifecycle.removeobserver(this) mainhandler.post { clear() } } } }
使用方式
class delegatefragment : fragment(r.layout.fragment_delegate) { private val binding : fragmentdelegatebinding by viewbindingv2(fragmentdelegatebinding::bind) override fun onviewcreated(view: view, savedinstancestate: bundle?) { super.onviewcreated(view, savedinstancestate) binding.tvname.text = "this is hello world" } }
到此这篇关于kotlin委托机制使用方式和原理的文章就介绍到这了,更多相关kotlin委托内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论