LoginSignup
1
0

Viewベースのプロジェクトにjetpack Composeを組み合わせる

Posted at

目的

・基本的にはXMLでレイアウト作ってアプリを作成していきたい。

・一部分だけjetpackComposeでつくりたい

・元々あるプロジェクトの一部分だけjetpackComposeに変えたい

というときに、ViewにjetpackComposeのViewを組み込む。

環境とか

・Android Studio Hedehog 2023.1.1 Patch 2
・MacOS Ventura
・プロジェクトはEmpty Views Activityで作成
・ViewBindingを使用

やり方

1.依存関係の追加

・EmptyViewsActivityで作成した場合、Compose関係の依存追加がされていないので追加

build.gladle(app)

buildFeatures{
        compose = true
    }
implementation("androidx.compose.material3:material3:1.2.0")
implementation("androidx.activity:activity-compose:1.8.2")
//↓プレビュー画面表示用
implementation("androidx.compose.ui:ui-tooling-preview:1.6.2")
debugImplementation("androidx.compose.ui:ui-tooling:1.6.2")

2.レイアウトにComposeViewを入れる
ButtonやTextViewなどと同じように入れればOK!


 <androidx.compose.ui.platform.ComposeView
        android:layout_marginTop="10dp"
        android:id="@+id/comp_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

3.アクティビティで呼び出し

class MainActivity : AppCompatActivity() {
    private lateinit var b: ActivityMainBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        b = ActivityMainBinding.inflate(layoutInflater)
        setContentView(b.root)
        b.compView.apply {
            setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
            setContent {
                //この中はjetpack Conposeのviewと同じ状態
                MaterialTheme {
                    homeList()//Composableなviewを呼びだし
                }
            }
        }
    }
    
}

これだけで、xmlでレイアウトしたViewにjetpackComposeを組み込むことができます
あとは、@ComposableでViewを作って呼び出すことができます

まとめ

・xmlレイアウトViewベースにjetpackComposeを組み込むのは簡単!
・UIや動作仕様に合わせて組み合わせて作るのもありでは?

参考サイト、詳細など

https://developer.android.com/jetpack/compose/migrate/interoperability-apis/compose-in-views?hl=ja
・ComposeメインのプロジェクトにViewを追加することもできます
https://developer.android.com/jetpack/compose/migrate/interoperability-apis/views-in-compose?hl=ja

1
0
0

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
1
0