I made a composable function which accept `context...
# compose
a
I made a composable function which accept
context
as input parameter while calling from
setContent
. How to use the same function calling from
@Preview
function
Copy code
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
           MainScreen(applicationContext)
        }
    }
}

@Composable
fun MainScreen(context: Context) { ...}

@Preview
@Composable
fun testPreview() {
    MainScreen( needToGetContextHere )
}
As in preview function we cannot pass any parameter. Is there any other approach to preview this ?? I think of one solution is to make
context
global. Is there any other better approach ??
a
This will let you grab a context from within a composable function
val context = +ambient(ContextAmbient)
, you don’t need to pass any parameters.
When I was shown this I was told that it would only return the
ApplicationContext
this may or may not be true now. Meaning that on configuration change you might not see new resources if you load them via the context. There are helper methods though for things like reading Strings, Drawables etc, so maybe use those instead if required.
a
@Andrew Kelly it is working thanks