Created
October 10, 2024 10:33
-
-
Save monday8am/f1e0b47c523a6451183fb78562b6d19d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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