Android JetPack Compose 構成リファレンス Android JetPack Compose 暫定版 1
RecyclerView コンポーネントの表示効果と同様に、このアプリケーションでスクロール可能なリスト インターフェイスを定義します。
1. エンティティクラスを定義する
data class Robot(val name:String,val desc:String,val imageId:Int)
名前、説明、および対応する画像リソース番号を表す 3 つの属性を含むエンティティ クラス Robot を定義します。
2. リスト項目を定義する
ロボット オブジェクトのリスト項目を表示します。
/**
* 定义显示机器人Robot实体信息的单项
* @param i Int
* @param robot Robot
*/
@Composable
fun RobotCard(context: Context, robot: Robot){
Box(modifier = Modifier
.fillMaxWidth()
.background(Color.Black)
.padding(10.dp)
.clip(shape = RoundedCornerShape(10.dp))
.border(width = 2.dp, color = Color.Blue, shape = RoundedCornerShape(10.dp))){
Row(content = {
Image(painter = painterResource(id = robot.imageId),
contentDescription = "${robot.name}的头像",
modifier = Modifier
.clip(shape = CircleShape)
.background(Color.Black)
.clickable {
Toast.makeText(context,"显示${robot.name}-${robot.desc}",Toast.LENGTH_LONG).show()
}
)
Column(modifier = Modifier.padding(10.dp)){
Text(text = "${robot.name}",
color = Color.Black,
fontWeight = FontWeight.Bold,
fontSize = 16.sp
)
Text(text="${robot.desc}",
color=Color.White,
fontWeight = FontWeight.Bold,
fontSize = 20.sp)
}
},
modifier=Modifier.fillMaxWidth().background(Color.Green).padding(20.dp))
}
}
3. スクロール可能なリストを定義する
/**
* 定义显示可滚动的机器人列表项
* @param robots List<Robot>
*/
@Composable
fun RobotsView(robots:List<Robot>){
var reverseLayout = false
var i = 1
LazyColumn(
state = rememberLazyListState(),
reverseLayout = reverseLayout,
verticalArrangement = if(!reverseLayout) Arrangement.Top else Arrangement.Bottom){
items(robots){robot->
RobotCard(LocalContext.current,robot = robot )
}
}
}
4. メインアクティビティMainActivity.ktを呼び出します。
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val robots = mutableListOf<Robot>()
for(i in 1..20){
robots.add(Robot("机器人 $i",
"Android机器人",android.R.mipmap.sym_def_app_icon))
}
setContent {
Ch04_ComposeTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
Column(content = {
RobotsView(robots = robots)
},
modifier = Modifier.fillMaxWidth()
.wrapContentHeight(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally)
}
}
}
}
}
実行結果は次のとおりです。
参考文献: