javaandroidkotlinandroid-jetpack-compose

Possible to use/lay out a Compose view in an Activity written in Java?


Google gives the following example of how to use a ComposeView in XML and inflate it in a fragment.

class ExampleFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        // Inflate the layout for this fragment
        return inflater.inflate(
            R.layout.fragment_example, container, false
        ).apply {
            findViewById<ComposeView>(R.id.compose_view).setContent {
                // In Compose world
                MaterialTheme {
                    Text("Hello Compose!")
                }
            }
        }
    }
}

I have an activity written in java, not kotlin. Is it possible to use setContent from a Java activity? If so I am struggling with the syntax.


Solution

  • Yes, it's possible.

    First you should create a subclass of AbstractComposeView:

    class MyComposeView
    @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) :
        AbstractComposeView(context, attrs) {
        @Composable
        override fun Content() {
            YourComposableFunction()
        }
    }
    

    and then set this view as Activity content...

    public class MyJavaActivity extends AppCompatActivity {
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(new MyComposeView(this));
        }
    }
    

    You can also declare your view in any layout file...

    <com.example.MyComposeView
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
    

    and call setContentView(R.layout.your_layout_file) as usual.