出现问题的场景是在使用Android Compose时,使用了约束布局(ConstraintLayout),但布局无法正常显示。
解决方法如下:
buildscript {
ext {
composeVersion = '1.0.0-alpha04'
}
dependencies {
classpath("com.android.tools.build:gradle:4.2.0-beta02")
}
}
plugins {
id 'org.jetbrains.kotlin.android' version '1.4.30'
id 'com.android.application'
id 'kotlin-android-extensions'
}
android {
compileSdkVersion 31
defaultConfig {
applicationId "com.example.androidcompose"
minSdkVersion 21
targetSdkVersion 31
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
composeOptions {
kotlinCompilerExtensionVersion = composeVersion
kotlinCompilerVersion = "1.4.30-beta"
}
}
dependencies {
implementation "androidx.constraintlayout:constraintlayout-compose:1.0.0-beta01"
implementation "androidx.compose.ui:ui:$composeVersion"
implementation "androidx.compose.foundation:foundation:$composeVersion"
implementation "androidx.compose.material:material:$composeVersion"
implementation "androidx.compose.runtime:runtime:$composeVersion"
implementation 'androidx.appcompat:appcompat:1.3.0-alpha02'
}
在布局文件中定义约束条件。
使用约束布局填充子元素。
示例代码:
ConstraintLayout(
modifier = Modifier.fillMaxSize()
) {
val (button1, button2) = createRefs()
Button(
onClick = { /* todo */ },
modifier = Modifier.constrainAs(button1) {
top.linkTo(parent.top, margin = 16.dp)
start.linkTo(parent.start, margin = 16.dp)
end.linkTo(parent.end, margin = 16.dp)
}
) {
Text("Button 1")
}
Button(
onClick = { /* todo */ },
modifier = Modifier.constrainAs(button2) {
top.linkTo(button1.bottom, margin = 16.dp)
start.linkTo(parent.start, margin = 16.dp)