|
// 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 |
|
} |
|
} |