Skip to main content

既存アプリにComposeを導入してみた

Androidの既存アプリにComposeを導入しようと思った
1画面入れるだけだったのに案外苦戦したので、そのまとめ


・Compose導入のライブラリ
https://developer.android.com/jetpack/compose/setup?hl=ja

implementation 'androidx.compose.ui:ui:1.2.1'
// Tooling support (Previews, etc.)
implementation 'androidx.compose.ui:ui-tooling:1.2.1'
// Foundation (Border, Background, Box, Image, Scroll, shapes, animations, etc.)
implementation 'androidx.compose.foundation:foundation:1.2.1'
// Material Design
implementation 'androidx.compose.material:material:1.2.1'
// Material design icons
implementation 'androidx.compose.material:material-icons-core:1.2.1'
implementation 'androidx.compose.material:material-icons-extended:1.2.1'
// Integration with activities
implementation 'androidx.activity:activity-compose:1.5.1'

・Compose previewのやり方

buildFeatures {
    compose true
}

 

・R.stringの読み込み
stringResource
https://developer.android.com/jetpack/compose/resources?hl=ja

・home as upをcomposeでやる
navigationIconで対応できる
https://stackoverflow.com/questions/72855651/how-to-create-a-topappbar-in-compose

・既存のアプリのthemeを使う
implementation “com.google.accompanist:accompanist-appcompat-theme:{version}”
をして以下をする

setContent {
    AppCompatTheme {
        Hoge()
    }
}

https://developer.android.com/jetpack/compose/interop/compose-in-existing-ui

・ComposeでFragmentをAttachする
AndroidViewを使ってupdateでcommitしてくっつける。
AndroidViewBindingはうまく動かなかった・・・・・
https://ticktakclock.hatenablog.com/entry/2021/11/04/211728
https://stackoverflow.com/questions/60520145/fragment-container-in-jetpack-compose

 

・エラー対応1
e: This version (1.2.0-alpha05) of the Compose Compiler requires Kotlin version 1.6.10 but you appear to be using Kotlin version 1.7.10 which is not known to be compatible. Please fix your configuration (or suppressKotlinVersionCompatibilityCheck but don’t say I didn’t warn you!).

build.gradleに以下を記載
バージョンはここに書いてある
https://developer.android.com/jetpack/androidx/releases/compose-kotlin

composeOptions {
    kotlinCompilerExtensionVersion = "1.3.1"
}

・エラー対応2
java.lang.NoSuchMethodError ‘void androidx.compose.material’
パッケージが足りてないだけなので足す
https://developer.android.com/jetpack/compose/setup?hl=ja

・エラー対応3
Content padding parameter it is not used
Scaffoldで囲ってcontentを使う場合はpaddingを引数に使う必要がある
https://stackoverflow.com/questions/72084865/content-padding-parameter-it-is-not-used

・エラー対応4
Unresolved reference: AndroidViewBinding

パッケージを入れて
implementation “androidx.compose.ui:ui-viewbinding:1.2.1”
設定を入れる

viewBinding {
    enabled = true
}

https://stackoverflow.com/questions/65366424/android-view-binding-unresolved-reference-in-multi-module-project

 

関連記事:

Pocket