Compose 可存取 Android 專案中定義的資源。
一樣使用xml 和 ViewBinding
android {
buildFeatures {
viewBinding true
// Enables Jetpack Compose for this module
compose true
}
...
}
dependencies {
// Integration with activities
implementation 'androidx.activity:activity-compose:1.5.1'
// Compose Material Design
implementation 'androidx.compose.material:material:1.2.1'
// Animations
implementation 'androidx.compose.animation:animation:1.2.1'
// Tooling support (Previews, etc.)
implementation 'androidx.compose.ui:ui-tooling:1.2.1'
// Integration with ViewModels
implementation 'androidx.lifecycle:lifecycle-viewmodel-compose:2.5.1'
// UI Tests
androidTestImplementation 'androidx.compose.ui:ui-test-junit4:1.2.1'
}
在 activity_main.xml 版面配置中,將 TextView 替換成 ComposeView,並保留相同的版面配置參數和 id。
範例是保留TextView 的版面配置參數和 id
多一個ComposeView 來看不同,實際就直接替換成 ComposeView,並保留相同的版面配置參數和 id。
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/greeting"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="30sp"
android:gravity="center"
android:textColor="@color/teal_200"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:text="Hello Android!" />
<androidx.compose.ui.platform.ComposeView
android:id="@+id/greeting2"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//viewBinding
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
//Compose
val greeting =findViewById<ComposeView>(R.id.greeting2)
greeting.setContent {
Greeting(name ="Android" )
}
}
}
@Composable
fun Greeting(name: String) {
Text(text = name+" "+stringResource(R.string.compose),
style = MaterialTheme.typography.h5,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp)
.wrapContentWidth(Alignment.CenterHorizontally)
)
}
上面是原有的TextView , 下方文字是用 ComposeView 的 Text
https://developer.android.com/jetpack/compose/interop/adding
Kotlin 的技術傳教士 - 范聖佑 近期也出了一本關於 Collection 的書 - Kotlin Collection 全方位解析攻略
裡面也有蠻多 operator 的介紹,歡迎大家有興趣的參考看看
https://www.tenlong.com.tw/products/9786263331136