Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Custom Views with Jetpack Compose

Let's suppose I'm using some library that's intended to provide some UI Widgets. Let's say this library provides a Button Widget called FancyButton.

In the other hand, I have a new project created with Android Studio 4 that allows me to create a new project with an Empty Compose Activity.

The question is: How should I add this FancyButton to the view stack? Is it possible? Or with Jetpack Compose I can only use components that had been developed specifically for Jetpack Compose. In this case, AFAIK I could only use Android standars components (Text, MaterialTheme, etc).

If I try to use something like this:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
        MaterialTheme {
            Greeting("Android")
            FancyButton(context, "Some text")
        }
    }
}

then I get this error:

e: Supertypes of the following classes cannot be resolved. Please make sure you have the required dependencies in the classpath.

like image 615
Joaquin Iurchuk Avatar asked Jan 30 '20 23:01

Joaquin Iurchuk


2 Answers

Currently (as of 0.1.0-dev04), there is not a good solution to this. In the future, you'll be able to simply call it as FancyButton("Some text") (no context needed).

You can see a demo of what it will look like in the Compose code here.

like image 97
Ryan M Avatar answered Nov 09 '22 04:11

Ryan M


Update in alpha 06

It is possible to import Android View instances in a composable.

Use ContextAmbient.current as the context parameter for the View.

Column(modifier = Modifier.padding(16.dp)) {

    // CustomView using Object
    MyCustomView(context = ContextAmbient.current)

    // If the state updates
    AndroidView(viewBlock = ::CustomView, modifier = modifier) { customView ->
        // Modify the custom view
    }

    // Using xml resource
    AndroidView(resId = R.layout.view_demo)
}

like image 26
Mahdi-Malv Avatar answered Nov 09 '22 06:11

Mahdi-Malv