【问题标题】:Error:(29, 34) Type mismatch: inferred type is String? but Editable! was expected错误:(29, 34) 类型不匹配:推断类型是字符串?但可编辑!预计
【发布时间】:2019-06-02 05:01:08
【问题描述】:
package com.example.acer.test

import android.content.Context
import android.content.SharedPreferences
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {

    private var sharedP: SharedPreferences? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        btn_add.setOnClickListener {
            sharedP = getSharedPreferences("addData", Context.MODE_PRIVATE)
            var myEditor = sharedP?.edit()
            myEditor?.putString("product_name" , et_productname.text.toString())
            myEditor?.commit()
            Toast.makeText(this@MainActivity, "The product is saved" , Toast.LENGTH_SHORT).show()


        }
        btn_get.setOnClickListener {
            et_getproduct.text = sharedP?.getString("product_name","null")
        }

    }
}

我需要从 Kotlin 中的 Shared 首选项中读取一个字符串,但它显示以下错误:Error:(29, 34) Type mismatch: inferred type is String?但可编辑!预料之中

【问题讨论】:

    标签: android kotlin


    【解决方案1】:

    你可以像这样创建一个扩展方法:

    fun String.toEditable(): Editable = Editable.Factory.getInstance().newEditable(this)
    

    然后像这样更改您的代码:

    btn_get.setOnClickListener {
                et_getproduct.text = sharedP?.getString("product_name","null").toEditable()
            }
    

    这是我用过的,效果很好

    【讨论】:

      猜你喜欢
      • 2022-11-14
      • 2019-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多