Software Development/Application Develop

Android Zetpack Compose 기초

huiyu 2024. 7. 27. 23:32

https://www.youtube.com/watch?v=xszyeIWFsGc&list=PLxTmPHxRH3VV8lJq8WSlBAhmV52O2Lu7n

@Composable -> 함수도 대문자로 시작.

@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
    Text(
        text = "Hello $name!",
        modifier = modifier
    )
}

setContent 안에 @composable 함수 사용 가능

setContent {
            MyApplicationTheme {
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    Greeting(
                        name = "Android",
                        modifier = Modifier.padding(innerPadding)
                    )
                }
            }
        }

 

@Preview를 통해 미리보기 가능

@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    MyApplicationTheme {
        Greeting("Android")
    }
}

 

모든 Compose객체는 Modifier로 객체 속성 설정 가능

    Box(modifier = Modifier.background(color = Color.Green)){
        Text("Hello")
    }
    Box(modifier = Modifier.background(color = Color.Green)
        .fillMaxSize()){
        Text("Hello")
    }

 

contentAlignment로 방향 설정

    Box(modifier = Modifier.background(color = Color.Green)
        .fillMaxSize(),
        contentAlignment = Alignment.Center
    ){
        Text("Hello")
    }

 

Column을 이용한 리스트

            val scrollState = rememberScrollState()

            Column(
                modifier = Modifier
                    .background(color = Color.Green)
                    .fillMaxWidth()
                    .verticalScroll(scrollState)
            ){
                for (i in 1..50) {
                    Text("글씨 $i")
                }
            }

 

LazyColumn

LazyColumn(
    modifier = Modifier
        .background(color = Color.Green)
        .fillMaxWidth()
){
    items(50) {index ->
        Text("$index")
    }
}
LazyColumn(
    modifier = Modifier
        .background(color = Color.Green)
        .fillMaxWidth(),
    contentPadding = PaddingValues(16.dp),
    verticalArrangement = Arrangement.spacedBy(8.dp)
){
    item{
        Text("Header")
    }
    items(50) {index ->
        Text("$index")
    }
    item{
        Text("Footer")
    }
}

 

Image / Card / State

fun ImageCard() {
    var isFavorite by remember {
        mutableStateOf(false)
    }
    Card(
        modifier = Modifier
            .fillMaxSize(0.5f)
            .padding(16.dp),
        shape = RoundedCornerShape(8.dp),
    ) {
        Box(
            modifier = Modifier.height(200.dp)
        ){
            Image(painter = painterResource(id = R.drawable.ic_launcher_background),
                contentDescription = "test",
                contentScale = ContentScale.Crop,
            )
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.TopEnd,
            ) {
                IconButton(onClick = {
                    isFavorite = !isFavorite
                }){
                    Icon(
                        imageVector = if (isFavorite) Icons.Default.Favorite else Icons.Default.FavoriteBorder,
                        contentDescrption = "favorite",
                        tint = Color.White
                    )
                }
            }
        }
    }
}

 

remember -> by로 사용 시 value값 사용 없이 사용


import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue

var isFavorite by remember {
        mutableStateOf(false)
    }

...

isFavorite = !isFavorite

값의 저장 필요할 경우, rememberSavable

    var isFavorite by rememberSaveable {
        mutableStateOf(false)
    }

 

isFavorite을 외부에서 저장하고 부를때,

1,. 아래와 같이 호출.

  var isFavorite by rememberSaveable {
                mutableStateOf(false)
    }
    ImageCard(
        isFavorite = isFavorite,
    ){
        favorite ->
        isFavorite = favorite
    }

 

2. 아래와 같이 인자로 함수 선언

@Composable
fun ImageCard(
    isFavorite: Boolean,
    onTabFavorite: (Boolean) ->Unit,
) {

 

3. OnTabFavorite는 OnClick시 bool값 반환 (.invoke는 생략 가능)

IconButton(onClick = {
    onTabFavorite(!isFavorite)
})

 

TextField에 입력 들어오는 값 입력하기

    var textValue = remember{
        mutableStateOf("")
    }
    TextField(
        value = textValue.value,
        onValueChange = {textValue.value = it},
    )
    Button(
        onClick = {}) {
            Text("클릭 !!")
    }

 

MutableState<T> 사용하기

@Stable
interface MutableState<T> : State<T> {
    override var value: T
    operator fun component1(): T
    operator fun component2(): (T) -> Unit
}

 

입력된 value 텍스트는 text로 component1 (구조분해)

onValueChange에 setValue를 정의하여 바로 set되게.

var (text, setvalue) = remember{
    mutableStateOf("")
}
TextField(
    value = text,
    onValueChange = setvalue,
)
Button(
    onClick = {}) {
        Text("클릭 !!")
}

 

scaffold를 이용한 snackbar

fun TextFunc(
) {
    var (text, setvalue) = remember{
        mutableStateOf("")
    }

    val scaffoldState = rememberScrollState()
    val scope = rememberCoroutineScope()
    val keyboardController = LocalSoftwareKeyboardController.current

    Scaffold(
        scaffoldState = scaffoldState,
    ) {
        Column(
            modifier = Modifier.fillMaxSize(),
            verticalArrangement = Arrangement.Center,
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            TextField(
                value = text,
                onValueChange = setvalue,
            )
            Button(
                onClick = {
                    scope.launch {
                        keyboardController.hide()
                        scaffoldState.snackbarHostState.showSnackbar("Hello")
                    }
                }) {
                Text("클릭 !!")
            }
        }
    }

 

728x90