我正在为 kotlin 应用程序开发一个演示,这些活动单独工作,但是当我尝试将它们与意图链接起来时,ntn 正在响应应该将您发送到下一个活动的按钮,但它只是不执行任何操作,并且在 logcat 上没有错误仅显示屏幕触摸位置的信息,所以请在尝试了一整天后我仍然看不到问题所在
package com.example.myapplication
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.AlarmClock.EXTRA_MESSAGE
import android.view.View
import android.widget.Button
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val tost:Button =findViewById(R.id.toast)
val nxt:Button =findViewById(R.id.next)
tost.setOnClickListener{tst()}
nxt.setOnClickListener{tnxt()}
}
private fun tst(){
Toast.makeText(this,"hello world",Toast.LENGTH_SHORT).show()
}
private fun tnxt(){
Intent(this, diceRoll::class.java)
startActivity(intent)
}
}
//和掷骰子类
package com.example.myapplication
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.dice_roll.*
class diceRoll : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.dice_roll)
var bttn:Button =findViewById(R.id.button)
bttn.setOnClickListener {
rolled()
}
}
private fun rolled(){
var txt:TextView=findViewById(R.id.no)
val randomInt=(1..6).random()
val resultStr=randomInt.toString()
txt.setText(resultStr)
}
}
简短回答:
更改您的功能
private fun tnxt(){
Intent(this, diceRoll::class.java)
startActivity(intent)
}
至:
private fun tnxt(){
startActivity(Intent(this, diceRoll::class.java))
}
问题:
使用这行
Intent(this, diceRoll::class.java)
,您正在创建一个Intent
,但永远不要使用它。
private fun tnxt(){
Intent(this, diceRoll::class.java)
startActivity(intent)
}
或者,
private fun tnxt(){
val diceRollIntent = Intent(this, diceRoll::class.java) //assigns the intent to a variable which we can use
startActivity(diceRollIntent)
}
有类似的问题。检查了 logcat。
我的 SecondActivity 试图使用 AppCompat 库中的一些功能,但我的应用程序中为此活动设置的主题并未继承自 Theme.AppCompat。
所以,我去
themes.xml
并将样式更改为继承自AppCompat。
<style name="Theme.MyApplication" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
</style>