Reputation: 167
I'm new to Android Native coding (Kotlin / Jetpack Compose) with a long background in AS3 Mobile App coding (OOP). I like to follow the same path and break Composable codes into smaller chunks, OOP, to make it easy to maintain.
For instance, this is the MainActivity:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MakeNav()
}
}
}
@Composable
fun MakeNav() {
var navCon = rememberNavController()
NavHost(navController = navCon, startDestination = "home") {
composable("home") {
MakeHome(navCon)
}
composable("list") {
MakeList()
}
}
}
And to compose the HomePage:
@Composable
fun MakeHome(navCon: NavController){
Box(
modifier = Modifier
.fillMaxSize()
){
Column() {
MakeHomeHdr()
MakeHomeBdy()
MakeHomeFtr(navCon)
}
}
}
Question:
For instance, in the MakeHomeBdy() I have 3 Variables which I need to pass to NavHost later:
var txtSub by rememberSaveable { mutableStateOf("Call Mr. X")}
var txtDte by rememberSaveable { mutableStateOf("1400/05/21")}
var txtTme by rememberSaveable { mutableStateOf("10:01")}
Column (
modifier = Modifier
.padding(30.dp)
){
TextField(
value = txtSub,
onValueChange = { txtSub = it },
placeholder = { Text("some text") },
modifier = Modifier
.fillMaxWidth()
)
...
When the Button in MakeHomeFtr() is clicked, I need to pass Data:
@Composable
fun MakeHomeFtr(navCon: NavController){
Row(
horizontalArrangement = Arrangement.End,
verticalAlignment = Alignment.Bottom,
modifier = Modifier.fillMaxSize()
) {
FloatingActionButton(
onClick = {navCon.navigate("list")},
modifier = Modifier
.padding(30.dp)
) {
Icon(Icons.Filled.Add, contentDescription = "Add")
}
}
}
In this example, I have no access to the Variables in MakeHomeBdy() to pass them to the NavHost:
NavHost(startDestination = "home") {
...
composable("list/{txtSub}/{txtDte}/{txtTme}") {...}
}
Where should I assign those Vars? What is the "Best" practice to build the code neat and clean, from beginning.
There are workarounds such as saving all Variables inside a Data Class, and access those from anywhere, which I don't think is correct. So what is the best way please?
Upvotes: 0
Views: 3249
Reputation: 167
Well, I think I found my own answer, that is, I can not think Old style and use New tools. This means rather than thinking OOP, I need to switch my mind to MVVM and follow the guidelines of Google:
https://developer.android.com/jetpack/guide
Upvotes: 0