首页 > 解决方案 > 取消参考参考视图

问题描述

我是 Kotlin 的新手,我不知道如何解决此错误:未解决的参考:查看。我的目标是按按钮转到其他活动。我复制代码:

class MainActivity : AppCompatActivity() {

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

        findViewById<Button>(R.id.button).setOnClickListener{
            sendMessage(view)
        }



    }

    val EXTRA_MESSAGE = "com.example.monedas.MESSAGE"
    fun sendMessage(it: view) {
        val intent = Intent(this, ListActivity::class.java)
        val editText : TextView = findViewById(R.id.textView4)
        val message = editText.text.toString()
        intent.putExtra(EXTRA_MESSAGE, message)
        startActivity(intent)
    }


}

标签: androidkotlinview

解决方案


您正在将未定义的参数传递给sendMessage()函数。
您尚未view在任何地方声明此变量。但似乎你不需要它,
因为你不需要it. 所以改为:sendMessage()

fun sendMessage() {
    val intent = Intent(this, ListActivity::class.java)
    val editText : TextView = findViewById(R.id.textView4)
    val message = editText.text
    intent.putExtra(EXTRA_MESSAGE, message)
    startActivity(intent)
}

并这样称呼它:

findViewById<Button>(R.id.button).setOnClickListener{
    sendMessage()
}


附带说明:在 Kotlin 中,如果您想访问活动类中膨胀布局的 s,则
不需要使用。 只需确保您已导入:findViewById()View

import kotlinx.android.synthetic.main.activity_main.*

然后你可以简单地做:

button.setOnClickListener{ sendMessage() }

并在sendMessage()

fun sendMessage() {
    val intent = Intent(this, ListActivity::class.java)
    intent.putExtra(EXTRA_MESSAGE, textView4.text)
    startActivity(intent)
}

推荐阅读