写完Compose第一个程序之后,接着了解Compose的布局。在Compose中有Column、Row和Box三种布局,其中Column是垂直布局,相当于把LinearLayout的orientation属性设置为vertical;Row是水平布局,相当于把LinearLayout的orientation属性设置为horizontal;Box是层叠布局,相当于FrameLayout。
import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.layout.* import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp class Compose_02Activity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { Compose_02_column(name = "002") } } } // 垂直排列 @Composable fun Compose_02_column(name: String){ Column { Compose_02_row(name) Spacer(modifier = Modifier.height(10.dp)) // 设置垂直排列两个控件间的距离 Compose_02_box() } } // 水平排列 @Composable fun Compose_02_row(name: String){ Row { Compose_01(name = "001") Spacer(modifier = Modifier.width(10.dp)) // 设置垂直排列两个控件间的距离 Text(text = "Compose_02,我是 $name!") } } // 层叠排列 @Composable fun Compose_02_box(){ Box { Image(painter = painterResource(id = R.drawable.ic_launcher_round), contentDescription = "放弃了放弃") Text(text = "放弃了放弃") } } //在AS预览界面 @Preview(showBackground = false) @Composable fun Compose_02_column(){ Compose_02_column("002") }
下面是程序运行的效果图: