Skip to content

Commit

Permalink
Update: get argument from Bundle, SavedStateHandle
Browse files Browse the repository at this point in the history
  • Loading branch information
doctor-blue committed Oct 4, 2021
1 parent ee40699 commit cbeb899
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 20 deletions.
1 change: 1 addition & 0 deletions .idea/gradle.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import androidx.navigation.compose.NavHost
import androidx.navigation.compose.rememberNavController
import com.devcomentry.composenavigation.ui.screen.*
import com.devcomentry.lib.composable
import com.devcomentry.lib.getParamFromArg
import com.devcomentry.lib.from

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
Expand All @@ -36,9 +36,10 @@ class MainActivity : AppCompatActivity() {

composable(Screen.Screen2, Screen2Argument()) {
// get data from arguments
Screen2(
it.arguments?.getParamFromArg(Screen2Argument()) as Screen2Argument
)
it.arguments?.let { bundle->
val argument = Screen2Argument().from(bundle)
Screen2(argument)
}
}

}
Expand Down
32 changes: 16 additions & 16 deletions lib/src/main/java/com/devcomentry/lib/Navigation.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,26 @@ import androidx.lifecycle.SavedStateHandle
import androidx.navigation.*
import androidx.navigation.compose.ComposeNavigator

fun Bundle.getParamFromArg(argument: Argument): Argument {
val fields = argument.javaClass.declaredFields
fun <T : Argument> T.from(bundle: Bundle): T {
val fields = this.javaClass.declaredFields
for (field in fields) {
field.isAccessible = true
if (field.name != "\$stable") {
field.set(argument, this[field.name])
if (field.name != "\$stable" && bundle.containsKey(field.name)) {
field.set(this, bundle[field.name])
}
}
return argument
return this
}

fun <T : Argument> T.from(state: SavedStateHandle): T {
val fields = this.javaClass.declaredFields
for (field in fields) {
field.isAccessible = true
if (field.name != "\$stable" && state.contains(field.name)) {
field.set(this, state[field.name])
}
}
return this
}

fun NavGraphBuilder.composable(
Expand Down Expand Up @@ -42,15 +53,4 @@ fun NavGraphBuilder.composable(
}
}
)
}

fun SavedStateHandle.get(argument: Argument): Argument {
val fields = argument.javaClass.declaredFields
for (field in fields) {
field.isAccessible = true
if (field.name != "\$stable") {
field.set(argument, this[field.name])
}
}
return argument
}

0 comments on commit cbeb899

Please sign in to comment.