Kotlin委托机制使用方式和原理

article/2025/8/29 4:01:32

目录

    • 类委托
    • 属性委托
    • 简单的实现属性委托
    • Kotlin标准库中提供的几个委托
      • 延迟属性Lazy
      • Lazy委托参数
      • 可观察属性Observable委托
      • vetoable委托
      • 属性储存在Map中
    • 实践方式
      • 双击back退出
      • Fragment/Activity传参
      • ViewBinding和委托

类委托

类委托有点类似于Java中的代理模式

interface Base{fun text()
}//被委托的类(真实的类)
class BaseImpl(val x:String): Base {override fun text() {println(x)}
}//委托类
class Devices(b:Base):Base by bfun main(){var b = BaseImpl("真实的类")Devices(b).text()
}

输出
在这里插入图片描述
委托类(代理类)持有真实类的对象,然后委托类(代理类)调用真实类的同名方法,最终真正实现的是方法的是真实类,这其实就是代理模式
kotlin中的委托借助于by关键字,by关键字后面就是被委托类

反编译成java代码

public final class BaseImpl implements Base {@NotNullprivate final String x;public BaseImpl(@NotNull String x) {Intrinsics.checkNotNullParameter(x, "x");super();this.x = x;}@NotNullpublic 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 fieldprivate 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 methodpublic 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 fieldstatic final KProperty[] $$delegatedProperties;@NotNullprivate final Text a$delegate = new Text();@NotNullpublic 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 {@NotNullpublic 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 methodpublic 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 {@NotNullprivate final kotlin.Lazy name$delegate;public Lazy() {this.name$delegate = kotlin.LazyKt.lazy( (Function0)null.INSTANCE);}@NotNullpublic 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 methodpublic 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 instanceprivate val lock = lock ?: thisoverride val value: Tget() {val _v1 = _valueif (_v1 !== UNINITIALIZED_VALUE) {@Suppress("UNCHECKED_CAST")return _v1 as T}return synchronized(lock) {val _v2 = _valueif (_v2 !== UNINITIALIZED_VALUE) {@Suppress("UNCHECKED_CAST") (_v2 as T)} else {val typedValue = initializer!!()_value = typedValueinitializer = nulltypedValue}}}override fun isInitialized(): Boolean = _value !== UNINITIALIZED_VALUEoverride 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 = 5println(c.age)c.age = 10println(c.age)c.age = 8println(c.age)c.age = 20println(c.age)
}

在这里插入图片描述
可以看到,当新值小于旧值,就会不生效

属性储存在Map中

class D(val map:Map<String,Any?>){val name:String by mapval 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 parametersprivate var param1: String? = nullprivate var param2: String? = nulloverride 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 fragmentreturn 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@JvmStaticfun 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 fragmentreturn 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@JvmStaticfun newInstance(param1: String, param2: String) =DelegateFragment().apply {this.param1 = param1this.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.KPropertyfun <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 ArrayListis 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? = nullprivate 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;}
}

通过委托的方式进行优化

  1. 委托ViewBinding.bind()的调用 -> 反射
  2. 委托destroy时binding = null的调用 -> 监听Fragment视图生命周期
  3. 想要binding属性声明为非空不可变变量val -> 属性委托ReadOnlyProperty<F,V>

编写委托类,详细内容可看注释

package com.example.memoryoptimizing.delegateimport 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? = nulloverride 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? = nulloverride 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"}}

http://www.hkcw.cn/article/wEEDDkymrF.shtml

相关文章

2025年能源科学与农业发展国际会议:共创可持续农业未来

会议简介 第二届能源环境科学与农业发展国际会议即将在武汉盛大召开。此次盛会定于武汉这一中部地区的中心城市举办&#xff0c;旨在汇聚国内外能源环境科学与农业发展的专家学者、企业家及各界精英&#xff0c;共同探讨能源资源的高效利用、环境保护的科技创新以及农业可持续发…

MongoDB(七) - MongoDB副本集安装与配置

文章目录 前言一、下载MongoDB1. 下载MongoDB2. 上传安装包3. 创建相关目录 二、安装配置MongoDB1. 解压MongoDB安装包2. 重命名MongoDB文件夹名称3. 修改配置文件4. 分发MongoDB文件夹5. 配置环境变量6. 启动副本集7. 进入MongoDB客户端8. 初始化副本集8.1 初始化副本集8.2 添…

未来楼宇自控系统升级优化,为绿色建筑发展注入更强动力支撑

在全球积极应对气候变化、大力推进节能减排的时代背景下&#xff0c;建筑行业作为能源消耗和碳排放的重点领域&#xff0c;其绿色转型迫在眉睫。绿色建筑旨在减少对环境的负面影响&#xff0c;实现资源高效利用&#xff0c;而楼宇自控系统作为建筑智能化的核心组成部分&#xf…

【SQL Server Management Studio 连接时遇到的一个错误】

第一次用SQL Server Management Studio启动之后第一步就是要建立连接 但是不知道Server Name要填什么&#xff0c;看了网上的教程说是要找到下面这个注册表中对应的实例名称填上去&#xff0c;或者前面加localhost 但是好像都没有用&#xff0c;一直遇到报错如下&#xff1a;…

华为云Flexus+DeepSeek征文 | 初探华为云ModelArts Studio:部署DeepSeek-V3/R1商用服务的详细步骤

华为云FlexusDeepSeek征文 | 初探华为云ModelArts Studio&#xff1a;部署DeepSeek-V3/R1商用服务的详细步骤 前言一、华为云ModelArts Studio平台介绍1.1 ModelArts Studio介绍1.2 ModelArts Studio主要特点1.3 ModelArts Studio使用场景1.4 ModelArts Studio产品架构 二、访问…

【Redis】string 类型

string 一. string 类型介绍二. string 命令set、getmget、msetsetnx、setex、psetexincr、incrby、decr、decrby、incrbyfloatappend、getrange、setrange、strlen 三. string 命令小结四. string 内部编码方式五. string 的应用场景缓存功能计数功能共享会话手机验证码 六. 什…

字体查看器

为了快速找到0不带点、斜杠的等宽字体&#xff0c;我做了个软件&#xff01; sonichy/HTYFontViewer

Java与Python优劣分析及两者联姻收奇功

Python 和 Java 作为两种广泛使用的编程语言&#xff0c;在大多数场景下都能实现相似的功能。但由于语言设计初衷、生态系统以及社区偏好的不同&#xff0c;Python 在某些特定领域确实具有 Java 难以比拟的天然优势。 一、以下是几个典型场景优劣分析 1. 快速原型开发与脚本化…

6.OpenFeign服务接口调用

目录 OpenFeign服务接口调用 一、openFeign简介 二、、OpenFeign 通用步骤 接口注解 流程步骤 1. 建Module 2. 添加POM依赖 3. 编写YML文件 4. 主启动(修改类名为MainOpenFeign80) 5.OpenFeign业务类编写 测试&#xff08;远程调用&#xff09; 三、OpenFeign高级特…

新能源汽车电控系统的精准守护者PKDV5355高压差分探头

在新能源汽车的"心脏"——电控系统中&#xff0c;每一次电流的精准切换都关乎车辆的性能与安全。PRBTEK PKDV5355高压差分探头就像一位经验丰富的"汽车医生"&#xff0c;帮助工程师们精准捕捉IGBT模块的每一次"心跳"&#xff0c;确保电驱系统健康…

资产生命周期管理:动态监控 + 精准管理

在数字化高度发展的当下&#xff0c;企业资产的范畴早已突破传统固定资产的局限&#xff0c;网络设备、服务器、软件系统等数字化资产在企业的日常运营与战略布局中扮演着越来越重要的角色。高效的资产管理体系对于优化资源配置、降低运营成本、确保业务不间断运行至关重要。 北…

MonoPCC:用于内窥镜图像单目深度估计的光度不变循环约束|文献速递-深度学习医疗AI最新文献

Title 题目 MonoPCC: Photometric-invariant cycle constraint for monocular depth estimation of endoscopic images MonoPCC&#xff1a;用于内窥镜图像单目深度估计的光度不变循环约束 01 文献速递介绍 单目内窥镜是胃肠诊断和手术的关键医学成像工具&#xff0c;但其…

华为OD机试真题——找终点(2025A卷:100分)Java/python/JavaScript/C/C++/GO最佳实现

2025 A卷 100分 题型 本专栏内全部题目均提供Java、python、JavaScript、C、C++、GO六种语言的最佳实现方式; 并且每种语言均涵盖详细的问题分析、解题思路、代码实现、代码详解、3个测试用例以及综合分析; 本文收录于专栏:《2025华为OD真题目录+全流程解析+备考攻略+经验分…

电路图识图基础知识-电路接线图(八)

识读电路接线图常识 1 电路接线图与电气原理图之间的关系 电气接线图是表示电气设备、元器件或装置等项目之间的连接关系&#xff0c;用来进行安装接线、 线路检查、线路检修和故障处理的一种简图。 在绘制电路接线图时必须依据相应的电气原理图&#xff0c;电路接线后必须达到…

基于python脚本进行Maxwell自动化仿真

本文为博主进行Maxwell自动化研究过程的学习记录&#xff0c;同时对Maxwell自动化脚本&#xff08;pythonIron&#xff09;实现方法进行分享。 文章目录 脚本使用方法脚本录制与查看常用脚本代码通用开头定义项目调整设计变量软件内对应位置脚本 设置求解器软件内对应位置脚本…

车载通信网络 --- CAN FD与CAN XL

我是穿拖鞋的汉子,魔都中坚持长期主义的汽车电子工程师。 老规矩,分享一段喜欢的文字,避免自己成为高知识低文化的工程师: 做到欲望极简,了解自己的真实欲望,不受外在潮流的影响,不盲从,不跟风。把自己的精力全部用在自己。一是去掉多余,凡事找规律,基础是诚信;二是…

Shell 脚本基础笔记

一 shell脚本概述 Shell 脚本是一种用 Shell 命令编写的脚本程序&#xff0c;用于在 Unix/Linux 系统的命令行环境中自动化执行任务。 它由一系列命令、逻辑控制语句&#xff08;如条件判断、循环&#xff09;和函数组成&#xff0c;保存为文本文件&#xff08;通常以 .sh 为扩…

sudo apt-get update错误解决

1.尝试sudo apt-get update发现很多无法命中且报错 首先使用 sudo vi /etc/resolv.conf 进入该文件后 代码如下&#xff1a; nameserver 8.8.4.4 nameserver 8.8.8.8然后按两次esc键&#xff0c;然后输入&#xff1a;wq 先输入 &#xff08;&#xff1a;&#xff09;再输…

管程机制 基本讲解

管程定义 构成要素&#xff1a;管程定义了一个数据结构&#xff0c;以及能为并发进程在该数据结构上执行的一组操作。 数据结构&#xff1a;例如在多进程共享资源场景中&#xff0c;可代表共享资源状态的变量集合&#xff0c;像共享文件读写状态、共享缓冲区占用情况等。一组操…

c#基础09(类与对象)

文章目录 类与对象面向对象概念封装访问修饰符 类如何定义类字段与属性 类的对象构造方法this关键字 类与对象 面向对象概念 并不是一个技术&#xff0c;而是一种编程指导思想。把现实世界的具体事物全部看出一个一个的对象来解决实际问题。 面向对象编程共同三大特性&#…