Issue
I have a compose screen in a fragment, and in that screen there is a button.
I want to dismiss the fragment/go back to previous screen when this button is pressed.
But I can't access any activity/fragment methods inside onClick.
How can I do that?
@AndroidEntryPoint
class MyFragment @Inject constructor() : Fragment(){
@ExperimentalComposeUiApi
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return ComposeView(requireContext()).apply {
this.setContent {
Button(
onClick = {
//Dismiss fragment.
},
) {
Text(
"Click me"
)
}
}
}
}
}
Solution
You can get the context inside any composable with LocalContext. You can get activity from this one, so you can use onBackPressed() or navigate in an other way:
val context = LocalContext.current
Button(
onClick = {
context.findActivity()?.onBackPressed()
},
) {
Text(
"Click me"
)
}
findActivity:
fun Context.findActivity(): Activity? {
var context = this
while (context is ContextWrapper) {
if (context is Activity) return context
context = context.baseContext
}
return null
}
Answered By - Philip Dukhov
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.