본문 바로가기

안드로이드 자바 코틀린 기초 지식/안드로이드 기초 지식

Jetpack Compose

안드로이드 개발자 구인글에 보면 Compose라고 적혀있는 이게 무엇인가???

 

Jetpack Compose는 안드로이드 앱의 UI를 쉽게 디자인하고 빌드하기 위한 라이브러리이다.

 

안드로이드는 xml내의 UI들을 Class에서 세팅을 해주고 Activity에서 UI를 어떻게 컨트롤 할 지 정의합니다.

그러나 이렇게 될경우 불필요한 코드량 증가와 가독성 떨어지고 이것은 내가 만들지 않은 코드를 유지보수를 할 때, xml과 class를 번갈아 보면서 선언된 뷰와 변수의 이름 등을 찾는 불편한 작업을 하는 일이 많다.

 

위와 같은 불편함을 해결할 새로운 UI 제작 방식이 Jetpack Compose 입니다.

 

Compose는 Kotlin의 특징을 이용해 선언형 프로그래밍으로 UI를 만듭니다.

더보기

선언형 프로그래밍?

  • 선언형 프로그래밍은 구현 방법은 신경쓰지 않고 무엇을 만들지 먼저 명령을 내리는 방식입니다. 
  • 구현 방식을 적지 않고 만드는 명령만 적기 때문에 상대적으로 직관적입니다.

Compose의 장점

1. 코드 감소 : 적은량의 코드로 보다 많은 작업을 하고 전체 버그 클래스를 방지할 수 있으므로 코드가 간단하며 유지 보수가 쉽습니다.

2. 직관성 : UI만 작성하면 나머지는 Compose가 처리합니다. 앱의 상태가 변경되면 UI가 자동으로 업데이트 됩니다.

3. 빠른 개발 과정 : 기존의 모든 코드와 호환되므로 언제든 사용할 수 있습니다. 실시간 미리보기 및 완전한 안드로이드 스튜디오 지원으로 빠르게 반복할 수 있습니다.

4. 강력한 성능 : 안드로이드 플랫폼 API에 직접 접근하고 머티리얼 디자인 등을 기본적으로 지원하는 멋진 앱을 만들 수 있습니다.

 

예제 :

1. build.gradle

android {
    buildFeatures {
        compose = true
    }

    composeOptions {
        kotlinCompilerExtensionVersion = "1.4.2"
    }
}
dependencies {

    val composeBom = platform("androidx.compose:compose-bom:2023.01.00")
    implementation composeBom
    androidTestImplementation composeBom

    // Choose one of the following:
    // Material Design 3
    implementation("androidx.compose.material3:material3")
    // or Material Design 2
    implementation("androidx.compose.material:material")
    // or skip Material Design and build directly on top of foundational components
    implementation("androidx.compose.foundation:foundation")
    // or only import the main APIs for the underlying toolkit systems,
    // such as input and measurement/layout
    implementation("androidx.compose.ui:ui")

    // Android Studio Preview support
    implementation("androidx.compose.ui:ui-tooling-preview")
    debugImplementation("androidx.compose.ui:ui-tooling")

    // UI Tests
    androidTestImplementation("androidx.compose.ui:ui-test-junit4")
    debugImplementation("androidx.compose.ui:ui-test-manifest")

    // Optional - Included automatically by material, only add when you need
    // the icons but not the material library (e.g. when using Material3 or a
    // custom design system based on Foundation)
    implementation("androidx.compose.material:material-icons-core")
    // Optional - Add full set of material icons
    implementation("androidx.compose.material:material-icons-extended")
    // Optional - Add window size utils
    implementation("androidx.compose.material3:material3-window-size-class")

    // Optional - Integration with activities
    implementation("androidx.activity:activity-compose:1.6.1")
    // Optional - Integration with ViewModels
    implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.5.1")
    // Optional - Integration with LiveData
    implementation("androidx.compose.runtime:runtime-livedata")
    // Optional - Integration with RxJava
    implementation("androidx.compose.runtime:runtime-rxjava2")

}

 

2. project level

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    ext {
        compose_version = '1.3.0-alpha01'
    }
}

plugins {
    id 'com.android.application' version '7.3.0' apply false
    id 'com.android.library' version '7.3.0' apply false
    id 'org.jetbrains.kotlin.android' version '1.8.10' apply false

}

task clean(type: Delete) {
    delete rootProject.buildDir
}
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Card
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.unit.dp
import androidx.fragment.app.Fragment


class ComposeFragment : Fragment() {
    private lateinit var mContext: Context

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mContext = context
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return ComposeView(requireContext()).apply {
            setContent {
                MessageCard(mContext)
            }
        }
    }
}

@Composable
fun MessageCard(mContext: Context) {
    Column(modifier = Modifier.padding(all = 8.dp)) {
        BookList(bookList, mContext)
    }
}

@Composable
fun BookList(books: List<Book>, context: Context) {
    LazyColumn() {
        items(books) { book ->
            BookListItem(book, context)
        }
    }
}

@Composable
fun BookListItem(book: Book, context: Context) {
    //Card 부분
    Card(
        shape = RoundedCornerShape(8.dp),
        elevation = 8.dp,
        modifier = Modifier
            .padding(16.dp)
    ) {
        Row(
            modifier = Modifier
                .padding(8.dp)
        ) {
            Column(
                modifier = Modifier
                    .padding(10.dp)
                    .fillMaxWidth()
                    .wrapContentSize(Alignment.Center)
            ) {
                Text(
                    text = book.bookTitle,
                    style = MaterialTheme.typography.subtitle1,
                    color = Color.Red
                )
                Text(
                    text = "by ${book.bookAuthor}",
                    style = MaterialTheme.typography.subtitle2,
                    color = Color.Blue,
                )

            }
        }
    }
}


//creating data class Book, which implements Parcelable
data class Book(
    val bookTitle: String,
    val bookAuthor: String
)

val bookList: List<Book> = listOf(
    Book("The Diary of A Young Girl", "Anne Frank"),
    Book("Alexander the Great", "Jacob Abbott"),
    Book("Autobiography of a Yogi", "Paramahansa Yogananda"),
    Book("Fluffy and Me", "Anita Krishan"),
    Book("My Inventions", "Nikola Tesla"),
    Book("The Enchanted Castle", "E. Nesbit"),
    Book("The Secret Garden", " Frances Hodgson Burnett")
)

 

나중에 한가할 때 어떤 내용들이 있는지 체크해보기

Row, Column, LazyColumn ... 이것저것 많은듯...

'안드로이드 자바 코틀린 기초 지식 > 안드로이드 기초 지식' 카테고리의 다른 글

DataBinding and ViewBinding  (0) 2023.03.08
다양한 Layout 들  (0) 2023.03.02
Rxjava  (0) 2023.03.02
LiveData  (0) 2023.03.01
Android JetPack  (0) 2023.02.28