Reputation: 3961
I have finished implementing this new Android jetpack navigation graph into a project. I have a ListView
that has a detailed view, defined in the nav graph.
The transitions to & from from view to view with this nav graph work great, however, I am stuck now trying to pass a data object from the ListView
(View A, comprised of Winter
objects) to the detailed view (View B). Before using Jetpack, this was quite simple with intents and startActivity()
Winter object:
class Winter(sportName:String, sportType: SportType, sportEquipment:ArrayList<Equipment> ) {
var sportName = ""
var sportType = WinterModel.SportType.board
var sportEquipment = arrayListOf<Equipment>()
enum class SportType(val type: String){
board("Board"),
ski("Ski"),
engine("Engine")
}
init {
this.sportName = sportName
this.sportType = sportType
this.sportEquipment = sportEquipment
}
}
I would like to be able to do something like:
val tappedSport = winterSport[position]
val bundle = Bundle()
bundle.putString(SPORT, tappedSport)
Navigation.findNavController(view!!).navigate(R.id.winterSportDetails,bundle)
Obviously that won't work, because winterSport[position] is not a string...
How can I pass the tapped Winter object to View B using jetpack navigation?
Edit: Here's how I would have done it with intents.
View A (Sending)
listView.setOnItemClickListener { _, _, position, _ ->
val tappedSport = winterSport[position]
val detailIntent = DetailActivity.newIntent(context, tappedSport)
startActivity(detailIntent)
}
View B (Receiving)
companion object {
const val SPORT_NAME = "SPORT_NAME"
const val SPORT_TYPE = "SPORT_TYPE"
const val SPORT_EQUIPMENT = "SPORT_EQUIPMENT"
fun newIntent(context: Context, sport: WinterModel): Intent {
val detailIntent = Intent(context, DetailActivity::class.java)
detailIntent.putExtra(SPORT_NAME, sport.sportName)
detailIntent.putExtra(SPORT_TYPE, sport.sportType.type)
detailIntent.putExtra(SPORT_EQUIPMENT, sport.sportEquipment.gear)
return detailIntent
}
}
//.. Then just access the info in onViewCreated
Upvotes: 1
Views: 1518
Reputation: 199805
The Extras of an Intent are stored in a Bundle. For every type that is acceptable in putExtra()
there is an equivalent method on Bundle that accepts that same type.
For example, for a String, you'd use putString
. Enum types are Serializable
, so you'd use putSerializable
. Similarly for every other type.
Upvotes: 3