我是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)
}
}发布于 2019-03-02 23:56:11
您正在向sendMessage()函数传递未定义的参数。
您还没有在任何地方声明这个view变量。
但是看起来你并不需要它,因为你不需要sendMessage()的参数it。
因此,更改为:
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中,如果您想要访问activity类中膨胀布局的View,则不需要使用findViewById()。
只需确保您已导入:
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)
}https://stackoverflow.com/questions/54960204
复制相似问题