我正在做一个类似于谷歌街景的虚拟导航应用程序。我通过微调器将用户的当前位置和目的地,然后将这些输入转换为字符串。但现在我想在我的NavigationDispalyActivity.kt中使用这些输入,但我不知道如何正确使用Intent。
我的代码
MainActivity.kt
package com.example.collegeroamer
import android.content.Intent
import android.os.Bundle
import android.widget.ImageButton
import android.widget.Spinner
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private lateinit var navigateButton: ImageButton
private lateinit var currentLocationSpinner: Spinner
private lateinit var destinationSpinner: Spinner
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
navigateButton = findViewById(R.id.navigateButton)
currentLocationSpinner = findViewById(R.id.currentLocationSpinner)
destinationSpinner = findViewById(R.id.destinationSpinner)
navigateButton.setOnClickListener {
val startingLocation = currentLocationSpinner.selectedItem.toString()
val destination = destinationSpinner.selectedItem.toString()
val intent = Intent(this, NavigationDisplayActivity::class.java)
intent.putExtra("selected_location", startingLocation)
startActivity(intent)
}
}
}
字符串
NavigationDisplayActivity.kt
@file:Suppress("UNUSED_EXPRESSION")
package com.example.collegeroamer
import android.os.Bundle
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
class NavigationDisplayActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_image_display)
val locationImage = findViewById<ImageView>(R.id.locationImage)
val selectedLocation = intent.getStringExtra("selected_location")
val imageResourceId = getImageResourceIdForLocation(selectedLocation ?: "")
locationImage.setImageResource(imageResourceId)
}
private fun getImageResourceIdForLocation(location: String): Int {
return when (location) {
else -> R.drawable.default_image
}
}
}
型
1条答案
按热度按时间2izufjch1#
您可以在Intent中传递多个键值对。每个键必须是唯一的,否则它将覆盖之前使用该键设置的任何内容。有关Intents的更多信息,您可以阅读开发人员文档here
您可以执行以下操作
字符串