Android Kotlin Application单例化 实例(自定义DelegatesExt,非自定义)

Android Studio Kotlin Application单例化 实例

第一种,是按照我们以前实现的单例模式

class FlashLight : Application() {
    companion object {
        // 按照我们在Java中一样创建一个单例最简单的方式:
        private var instance:Application?=null;
        fun instance()= instance!!;
            }
    override fun onCreate() {
        super.onCreate()
        instance=this;

    }

}

第二种,使用Kotlin自带的单例模式,使用notNull委托

class FlashLight : Application() {
    companion object {
       // 单例不会是null   所以使用notNull委托
     var instance: FlashLight by Delegates.notNull()

    }
    override fun onCreate() {
        super.onCreate()
        instance=this;

    }

}

第三种,Kotlin库提供了几个接口,我们自己的委托必须要实现的几个接口,自定义单例模式,创建一个DelegatesExt.kt文件

/**
 * Created by Jeff on 2018-02-1.
 * Email : 15899859876@qq.com.
 */
object DelegatesExt {
    //现在你可以创建一个对象,然后添加函数使用你的委托:
    fun <T> notNullSingleValue(): ReadWriteProperty<Any?, T> = NotNullSingleValueVar()
    fun <T> getPreference(context: Context, name: String, default: T): ReadWriteProperty<Any?, T> = Preference(context, name, default)
}

/**
* Kotlin库提供了几个接口,我们自己的委托必须要实
* 现: ReadOnlyProperty 和 ReadWriteProperty 。具体取决于我们被委托的对
* 象是 val 还是 var 。
* 我们要做的第一件事就是创建一个类然后继承 ReadWriteProperty */
class NotNullSingleValueVar<T> : ReadWriteProperty<Any?, T> {

    private var value: T? = null
//Getter函数 如果已经被初始化,则会返回一个值,否则会抛异常。
    override fun getValue(thisRef: Any?, property: KProperty<*>): T {
        return value ?: throw IllegalStateException("${property.name} not initialized")
    }

    //Setter函数 如果仍然是null,则赋值,否则会抛异常。
    override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
        this.value = if (this.value == null) value else throw IllegalStateException("${property.name} not initialized")
    }
}

/**
 * 泛型preference委托
 * 访问Shared Preferences
 * **/
class Preference<T>(val context: Context, val name: String, val default: T) : ReadWriteProperty<Any?, T> {

    val ref: SharedPreferences by lazy { context.getSharedPreferences("News", Context.MODE_PRIVATE) }

    override fun getValue(thisRef: Any?, property: KProperty<*>): T {
        return findPreferenceByName(name, default)
    }

    override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
        putPreference(name, value)
    }

    private fun findPreferenceByName(name: String, default: T): T = with(ref) {
        val res: Any = when (default) {
            is Int -> getInt(name, default)
            is Boolean -> getBoolean(name, default)
            is String -> getString(name, default)
            is Long -> getLong(name, default)
            is Float -> getFloat(name, default)
            else -> throw IllegalArgumentException("this type not support")
        }
        return res as T
    }

    private fun putPreference(name: String, value: T) = with(ref.edit()) {
        when (value) {
            is Int -> putInt(name, value)
            is Boolean -> putBoolean(name, value)
            is String -> putString(name, value)
            is Long -> putLong(name, value)
            is Float -> putFloat(name, value)
            else -> throw IllegalArgumentException("this type not support")
        }.apply()
    }

}

在application里调用上面自定义的DelegatesExt

/**
 * Created by Jeff on 2018-02-1.
 * Email : 15899859876@qq.com.
 */
class FlashLight : Application() {

    companion object {
        // 按照我们在Java中一样创建一个单例最简单的方式:
//        private var instance:Application?=null;
//        fun instance()= instance!!;
       // 单例不会是null   所以使用notNull委托
     //var instance: FlashLight by Delegates.notNull()
        // 自定义委托实现单例,只能修改这个值一次.
        var instance: FlashLight by DelegatesExt.notNullSingleValue<FlashLight>()
    }
    override fun onCreate() {
        super.onCreate()
        instance=this;

    }

}

直接调用 instance就可以了,或着使用FlashLight. instance

Toast.makeText( instance, “Hello, views!”, LENGTH_SHORT).show();
Toast.makeText( FlashLight. instance, “Hello, views!”, LENGTH_SHORT).show();

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现 Android Kotlin 按钮展示 Spinner 的自定义样式,可以按照以下步骤进行: 1. 在布局文件添加一个 Button 控件和一个隐藏的 Spinner 控件: ```xml <Button android:id="@+id/btn_spinner" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Select Item"/> <Spinner android:id="@+id/spinner" android:layout_width="0dp" android:layout_height="0dp" android:visibility="gone"/> ``` 2. 在 Kotlin 代码设置 Button 的点击事件: ```kotlin btn_spinner.setOnClickListener { spinner.performClick() } ``` 3. 创建一个自定义的 Spinner 样式,例如: ```xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="16dp"> <ImageView android:id="@+id/img_icon" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher"/> <TextView android:id="@+id/tv_item_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:text="Item Name" android:textSize="16sp"/> </LinearLayout> ``` 4. 创建一个自定义的 Spinner 适配器: ```kotlin class CustomSpinnerAdapter(private val context: Context, private val items: List<String>) : ArrayAdapter<String>(context, 0, items) { override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { var view = convertView if (view == null) { view = LayoutInflater.from(context).inflate(R.layout.item_spinner, parent, false) } val tvItemName = view?.findViewById<TextView>(R.id.tv_item_name) tvItemName?.text = items[position] return view!! } override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View { var view = convertView if (view == null) { view = LayoutInflater.from(context).inflate(R.layout.item_spinner_dropdown, parent, false) } val tvItemName = view?.findViewById<TextView>(R.id.tv_item_name) tvItemName?.text = items[position] return view!! } } ``` 5. 在 Kotlin 代码设置 Spinner 的适配器和选择事件: ```kotlin val items = listOf("Item 1", "Item 2", "Item 3") val adapter = CustomSpinnerAdapter(this, items) spinner.adapter = adapter spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { btn_spinner.text = items[position] } override fun onNothingSelected(parent: AdapterView<*>?) { // Do nothing } } ``` 这样就可以实现一个自定义样式的 Spinner,展示在一个 Button 控件上。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值