将多个值传递给另一个活动在我的Android项目中不起作用。我想创建设置菜单活动,以传递android中应用程序的设置值。这些值由诸如开关和数字选择器之类的小部件设置。
这是我的MenuActivity女巫从传递的线索
const val EXTRA_VALUE1="com.exapmple.MyApplication.SETTING"
const val EXTRA_VALUE2="com.exapmple.MyApplication.SETTING"
const val EXTRA_VALUE3="com.exapmple.MyApplication.SETTING"
const val EXTRA_VALUE4="com.exapmple.MyApplication.SETTING"
class MenuActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(com.example.bowlingo.R.layout.activity_menu)
var value1 = 0
var value2 = 1
var value3 = 1
val switch1: Switch = findViewById(R.id.switch1)
switch1.setOnCheckedChangeListener { _, isChecked ->
if (isChecked)
value1 = 1
}
val switch2: Switch = findViewById(R.id.switch2)
switch2.setOnCheckedChangeListener { _, isChecked ->
if (isChecked)
value2 = 0
}
val switch3: Switch = findViewById(R.id.switch3)
switch3.setOnCheckedChangeListener { _, isChecked ->
if (isChecked)
value3 = 0
}
val numPicker = findViewById<NumberPicker>(R.id.numPicker)
numPicker.wrapSelectorWheel = false
val values = arrayOf("3", "5", "7")
numPicker.minValue = 0
numPicker.maxValue = values.size-1
numPicker.displayedValues = values
val vlue4= numPicker.value
val start: Button = findViewById(R.id.start)
start.setOnClickListener { // Handler code here.
val intent = Intent(this@MenuActivity, MainActivity::class.java).apply {
putExtra(EXTRA_VALUE1, value1)
putExtra(EXTRA_VALUE2, value2)
putExtra(EXTRA_VALUE3, value3)
putExtra(EXTRA_VALUE4, value4)
}
startActivity(intent);
}
}
}
这是MainActivity获取值的一部分
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val value1 = intent.getIntExtra(EXTRA_VALUE1,0)
val value2 = intent.getIntExtra(EXTRA_VALUE2,0)
val value3 = intent.getIntExtra(EXTRA_VALUE3,0)
val value4 = intent.getIntExtra(EXTRA_VALUE4,0)
val textView = findViewById<TextView>(R.id.textView).apply {
text = value1.toString() +":" + value2.toString() +":" + value3.toString()+ ":" + value4.toString()
}
}
MainAtivity上的textView始终显示“ 1:1:1:1”,如果我点击开关和数字小键盘,它不会改变。谁能帮我。
您需要为每个常量使用不同的值。因为现在您只从EXTRA_VALUE1
中接收值
例如:
const val EXTRA_VALUE1="com.exapmple.MyApplication.SETTING_1"
const val EXTRA_VALUE2="com.exapmple.MyApplication.SETTING_2"
const val EXTRA_VALUE3="com.exapmple.MyApplication.SETTING_3"
const val EXTRA_VALUE4="com.exapmple.MyApplication.SETTING_4"
您的问题是,代表额外数据的所有字符串(EXTRA_VALUE1
,EXTRA_VALUE2
,...)具有相同的字符串值。您需要给他们一个不同的字符串,否则您只是在写以前的值。