Column & Row & Text
1) 일반적으로 Jetpack Compose 에서 Column Composable 은 수직으로 배치하고자 할 때 사용하고, Row Composable 은 수평으로 배치하고자 할 때 사용한다.
2) Spacer 는 공백을 주고 싶을 때 사용하는 Composable.
3) dp 단위는 보통 Int 값 뒤에 dp 를 붙여서 사용한다.
4) Modifier : 길이를 조정하고자 할 때, 그 외, 속성을 변경하고자 할 때, Modifier를 사용한다. 선언한 순서대로 차례대로 지정된다. .fillMaxSize() 는 화면 전체를 채우고 싶을 때 사용하는 속성이다.
5) @Composable 은 대문자로 선언해야 한다. @Preview annotation 은 미리보기로 Android Studio 내에서 Split 버튼을 선택하여 볼 수 있다. 더불어 다른 이름으로 여러개 선언 및 확인이 가능하다.
6) Sample Code
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
FirstComposeExampleTheme {
Surface(color = MaterialTheme.colorScheme.background) {
Column (modifier =
Modifier
.fillMaxSize()
.background(color = androidx.compose.ui.graphics.Color.Blue)
.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Text("Hello")
Text("World")
}
}
}
}
}
}
Box
1) 간단하게 Column Composable, Row Composable이 LinearLayout 이라고 한다면, Box Composable은 FrameLayout 이라고 생각하면 편하다. Box Compose는 Text Composable 을 그냥 선언하기만 하면 안에 있는 Child가 다 겹쳐서 보이게 된다.
2) Modifier Attribute 정리
fillMaxSize | Width && Height |
fillMaxHeight | Only Height |
fillMaxWidth | Only Width |
3) Sample Code
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
FirstComposeExampleTheme {
Box(modifier = Modifier.background(color = androidx.compose.ui.graphics.Color.Green)
.fillMaxWidth()
.height(200.dp),
) {
Text("Hello")
Box(
modifier = Modifier.fillMaxSize()
.padding(16.dp),
contentAlignment = Alignment.BottomEnd
) {
Text("Hello")
}
}
}
}
}
}
리스트, LazyColumn
1) 100 개의 목록으로 구성된 view를 구성하고자 할 때, 전에는 RecylerView를 사용했다면, 이제는 LazyColumn 을 사용해서 처리한다. RecylerView는 말 그대로, 하위 항목을 재사용했지만, LazyColumn 은 재사용하지 않는다. 스크롤에 따라 새로운 Composable 객체를 만든다.
2) Sample Code
LazyColumn(
modifier = Modifier
.background(color = androidx.compose.ui.graphics.Color.Cyan)
.fillMaxWidth(),
contentPadding = PaddingValues(16.dp),
verticalArrangement = Arrangement.spacedBy(4.dp)
) {
items(50) { index ->
Text("test $index")
}
}
3) *Jetpack Compose는 setContent 부터 시작한다. setContent 위는 Jetpack Compose에서 쓸 수 있는 영역이 아니다.
4) LazyColumn 에서는 하기에 적힌 Sample code 와 같이 for 문으로 접근하는 것이 허용되지 않고, items로 접근이 가능하다. 하기의 코드는 LazyColumn 으로 스크롤을 적용하지 않았을 때의 코드이며, 실제로는 LazyColumn 을 더 많이 쓴다. 참고하자.
5) Sample Code - 2
val scrollState = rememberScrollState()
setContent {
val scrollState = rememberScrollState()
Column(
modifier = Modifier
.background(color = androidx.compose.ui.graphics.Color.Cyan)
.fillMaxWidth()
.verticalScroll(scrollState)
) {
for (i in 1..50) {
Text("Text $i")
}
}
6) contentPadding 은 설정한 값으로 사방에 padding 두르기 가능하다.
7) Arrangement.spacedBy 은 item 간의 space 설정이 가능하다.
8) items 의 상,하단에 item 로 "header", "footer" 만들기도 가능하다.
Card, State
1) Card compose는 Android에서 CardView와 유사한 기능을 하는 Composable 이다.
2) Image는 drawable 폴더에 배치해두기
3) Compose 에서 상태를 기억하게 하는 방법은 remember 키워드를 사용하는 것이다. 이때, .value 를 쓰기 귀찮다면, 다음과 같이 delegate property 인 by 를 사용하면 된다.
val isFavorite = remember {
mutableStateOf(false)
}
다음과 같이 사용 가능하다.
var isFavorite by remember {
mutableStateOf(false)
}
Icon(
imageVector = if(isFavorite) Icons.Default.Favorite else Icons.Default.FavoriteBorder,
contentDescription = "Favorite",
tint = androidx.compose.ui.graphics.Color.White,
)
4) 안드로이드는 화면 초기화(가로/세로 변환) 시, 값이 초기화되는데, 이 때, rememberSaveable 사용하면 된다.
5) isFavorite 를 변수로 받아오면, 상수로 들어가서, 변경을 할 수 없다. 그래서 콜백으로 수정이 필요하다.
IconButton(onClick = {
onTabFavorite(!isFavorite)
})
setContent {
// 상태값 변경 시, UI가 다시 그려짐. 상수인 val 로 처리 가능.
// by 를 쓰면 return 값이 변함. Boolean.
var isFavorite by rememberSaveable {
mutableStateOf(false)
}
ImageCard(
isFavorite = isFavorite,
) { favorite ->
isFavorite = favorite
}
}
6) modifier 를 ImageCard Composable 이 아닌, 외부에서 재사용성을 위해 선언해둘 수 도 있다. ImageCard의 Modifier 는 기본값으로 지정해두고, setContent 내에서 modifier 설정한 예제 코드는 다음과 같다.
7) Sample Code
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
// 상태값 변경 시, UI가 다시 그려짐. 상수인 val 로 처리 가능.
// by 를 쓰면 return 값이 변함. Boolean.
var isFavorite by rememberSaveable {
mutableStateOf(false)
}
ImageCard(
modifier = Modifier.fillMaxWidth(0.5f)
.padding(16.dp),
isFavorite = isFavorite,
) { favorite ->
isFavorite = favorite
}
}
}
}
@Composable
fun ImageCard(
modifier : Modifier = Modifier,
isFavorite: Boolean,
onTabFavorite: (Boolean) -> Unit,
) {
Card(
modifier = modifier,
shape = RoundedCornerShape(8.dp),
) {
Box(
modifier = Modifier.height(200.dp),
){
Image(
painter = painterResource(id = R.drawable.kuromi),
contentDescription = "kuromi",
contentScale = ContentScale.Crop,
)
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.TopEnd,
) {
IconButton(onClick = {
onTabFavorite(!isFavorite)
}) {
Icon(
imageVector = if(isFavorite) Icons.Default.Favorite else Icons.Default.FavoriteBorder,
contentDescription = "Favorite",
tint = androidx.compose.ui.graphics.Color.White,
)
}
}
}
}
}
'[ Jetpack Compose ]' 카테고리의 다른 글
News Application Clone #2 (0) | 2023.11.14 |
---|---|
News Application Clone #1 (0) | 2023.11.08 |
Jetpack Compose Basic #4 (0) | 2023.11.07 |
Jetpack Compose Basic #3 (0) | 2023.11.02 |
Jetpack Compose Basic #2 (0) | 2023.10.30 |