Skip to content

Instantly share code, notes, and snippets.

@monday8am
Created October 10, 2024 10:33
Show Gist options
  • Save monday8am/410d8561bb95874a39e13b1ab75aaa8f to your computer and use it in GitHub Desktop.
Save monday8am/410d8561bb95874a39e13b1ab75aaa8f to your computer and use it in GitHub Desktop.
Navigation example
// Define an interface for navigation keys
interface NavigationKey : Parcelable
// Example implementation for a specific screen
@Parcelize
data class ProfileKey(val userId: String) : NavigationKey
// Navigation manager class
class Navigator(private val context: Context) {
fun navigate(key: NavigationKey) {
val intent = when (key) {
is ProfileKey -> Intent(context, ProfileActivity::class.java).apply {
putExtra(EXTRA_USER_ID, key.userId)
}
// Add other cases for different NavigationKey implementations
else -> throw IllegalArgumentException("Unknown navigation key: $key")
}
context.startActivity(intent)
}
companion object {
const val EXTRA_NAVIGATION_KEY = "extra_navigation_key"
const val EXTRA_USER_ID = "extra_user_id"
}
}
// Usage in an Activity
class MainActivity : AppCompatActivity() {
private lateinit var navigator: Navigator
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
navigator = Navigator(this)
findViewById<Button>(R.id.btnOpenProfile).setOnClickListener {
navigator.navigate(ProfileKey("user123"))
}
}
}
// Retrieving the key in the destination Activity
class ProfileActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_profile)
val userId = intent.getStringExtra(Navigator.EXTRA_USER_ID)
// Use userId to load profile data
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment