LoginSignup
3
4

More than 3 years have passed since last update.

既存のレイアウトの一部にJetpack Composeを組み込む

Posted at

はじめに

Google I/O 2021でアナウンスされたように、今後Jetpack ComposeでUIを組み込んでいくのが推奨されていくようです。
そこで、本記事では既存のアプリにJetpack Composeを組み込む方法を説明します。

既存のアプリにJetpack Composeを組み込む

レイアウト

レイアウトファイルの一部でComposeを使う時の例です。

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/hello"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world"
        android:layout_marginTop="20dp"
        android:layout_marginBottom="20dp"
        android:textSize="20sp"
        android:textColor="@color/black"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>

    <androidx.compose.ui.platform.ComposeView
        android:id="@+id/compose"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@id/hello"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

通常のレイアウトファイルでComposeを使いたい箇所にComposeViewを記述します。
このComposeView内にコード上でCompose関数を使うことになります。

Compose関数の追加

上記のレイアウトをActivity内でCompose関数と一緒に使う時の例です。

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        findViewById<ComposeView>(R.id.compose).setContent { 
            Greeting(message = "Hello Compose!")
        }
    }

    @Composable
    fun Greeting(message: String) {
        Text(text = message, fontSize = 20.sp, textAlign = TextAlign.Center)
    }
}

ComposeViewを取得して、それに対してsetContentブロックを定義します。
そのブロック内でCompose関数を呼び出す等して、ComposeでUIを記述できます。

完成イメージ

screenshot.png

おわりに

今回は既存のxmlで実装したレイアウトの一部にComposeで実装したレイアウトを組み込む方法を説明しました。
比較的簡単に組み込めるので、徐々にComposeで実装する部分を増やしていくことはできると思います。

参考

Jetpack Composeを使ってみる | Android Developers

3
4
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4