Jetpack Compose ๊ณต์๋ฌธ์
[์๋ ๋ด์ฉ์ ๊ณต์๋ฌธ์๋ฅผ ์ฐธ๊ณ ํ์์ต๋๋ค.]
SOPT 34๊ธฐ ์๋๋ก์ด๋ ํํธ ๋ฉด์ ์ค "compose
๋ฅผ ์ ์ฉํ๊ณ ๋ฐฐ์์ผ ํ๋ ์ด์ ๋ ๋ญ๊ฐ์?"๋ผ๋ ์ง๋ฌธ์ ๋ฐ์์๋ค.
๊ทธ๋๋ ์ปดํฌ์ฆ๋ฅผ ์ ํ๊ธฐ ์ ์ด์๊ณ , 'compose
๊ณต๋ถ๋ฅผ ํด์ผํ๋ค'๋ผ๋ ์ด์ผ๊ธฐ๋ฅผ ๊ต์ฅํ ๋ง์ด ๋ค์๋ ์๊ธฐ๋ผ ๋น์ฐํ ๊ณต๋ถํด์ผํ๋ ์กด์ฌ๋ผ๊ณ ๋ง ์ฌ๊ฒผ๋ค.
๊ทธ๋ ๋ค๋ฉด ์ด๋ ๊ฒ compose
๋ฅผ ๋น์ฐํ ํด์ผํ๋ค๊ณ ๋ง์ ์ด๋ค์ด ๋งํ๋ ์ด์ ๋ ๋ฌด์์ผ๊น?
์ ์ ์ฝ๋๋ ํ
์คํธ/๋๋ฒ๊ทธ ์์
์ด ์ ๊ณ ๋ฒ๊ทธ ๋ฐ์๊ฐ๋ฅ์ฑ๋ ์ค์ด๋ ๋ค.
๋ํ ์ฝ๋๊ฐ ์ ๋ค๋ ๊ฑด ๊ทธ๋งํผ ์ ์ง๋ณด์ ํด์ผํ๋ ์ฝ๋๋ ์ค์ด๋ ๋ค๋ ์ด์ผ๊ธฐ์ด๋ค.
Compose
@Composable
fun Greeting() {
Column {
Text(text = "Hello, Compose!", color = Color.Black, fontSize = 20.sp)
}
}
xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, XML!"
android:textSize="20sp"
android:textColor="@android:color/black"
android:layout_gravity="center"/>
๊ธฐ์กด xml ๋ฐฉ์์ view์ data ์ฌ์ด์ ์ค๊ฐ ๊ณ์ธต์ ํ์๋กํ๋ค.
๊ทธ๋์ xml์ ์์ ํ๋ฉด ์ฝํ๋ฆฐ์ฝ๋๋ ํจ๊ป ์์ ์ ํ๋ ๋ฑ xml๊ณผ ์ฝํ๋ฆฐ ์ฝ๋๋ฅผ ๊ฐ์ด ๋ด์ผํ๋ค.
ํ์ง๋ง
compose
์ ๊ฒฝ์ฐ ์ฝํ๋ฆฐ ํจ์๋ก UI๋ฅผ ๊ทธ๋ฆฌ๊ธฐ ๋๋ฌธ์ ๋ ์ง๊ด์ ์ด๊ณ ์ดํดํ๊ธฐ ์ฝ๋ค. ๋ํ ์ ์ง๋ณด์ ์ธก๋ฉด์์๋ ์ด๋ก์ธ ์ ์๋ค.
<Button
android:id="@+id/myButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me!"
android:background="@color/blue"
android:textColor="@android:color/white"
android:layout_centerInParent="true"/>
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val myButton = findViewById<Button>(R.id.myButton)
myButton.setOnClickListener {
Toast.makeText(this, "Button clicked!", Toast.LENGTH_SHORT).show()
}
}
}
์ ์ฝ๋๋ ์กํฐ๋นํฐ์ onCreate
๋ฉ์๋์์ XML ํ์ผ์์ ์ ์๋ ๋ฒํผ์ ์ฐพ์ ํด๋ฆญ ์ด๋ฒคํธ๋ฅผ ์ฒ๋ฆฌํ๋ ๋ฐฉ๋ฒ์
๋๋ค.
์ด ๊ฒฝ์ฐ๋ ๋ฒํผ์ ํด๋น ์กํฐ๋นํฐ์ ์ข ์๋์ด์๋ค.
@Composable
fun MyButton(text: String, onClick: () -> Unit) {
Button(
onClick = onClick,
colors = ButtonDefaults.buttonColors(backgroundColor = Color.Blue)
) {
Text(text = text, color = Color.White)
}
}
์์ ์ฝ๋์์ MyButton
ํจ์๋ ์ํ ์๋ ๋ฒํผ ์ปดํฌ๋ํธ๋ฅผ ์ ์ํ๋ค.
์ด ๋ฒํผ์ ํ ์คํธ์ ํด๋ฆญ ์ด๋ฒคํธ๋ฅผ ๋งค๊ฐ๋ณ์๋ก ๋ฐ๊ณ , ๋ฒํผ์ ํด๋ฆญํ๋ฉด ์ ๋ฌ๋ ํด๋ฆญ ํธ๋ค๋ฌ๊ฐ ํธ์ถ๋๋ค.
์ด๋ ๊ฒ ์ ์๋ ๋ฒํผ ์ปดํฌ๋ํธ๋ ํน์ ํ ์กํฐ๋นํฐ๋ ํ๋๊ทธ๋จผํธ์ ์ข ์๋์ง ์์ผ๋ฏ๋ก ๋ค๋ฅธ ํ๋ฉด์์ ์ฝ๊ฒ ์ฌ์ฌ์ฉO
Compose๋ ๊ธฐ์กด์ ๋ชจ๋ ์ฝ๋์ ํธํ๋๋ค.
Compose์์ Views๋ฅผ, Views์์ Compose ์ฝ๋๋ฅผ ํธ์ถ โญ๏ธ
Navigation, ViewModel, Kotlin ์ฝ๋ฃจํด๊ณผ ๊ฐ์ ๋๋ถ๋ถ์ ์ผ๋ฐ์ ์ธ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ Compose์ ํจ๊ป ์๋ํ๋ฏ๋ก ์ธ์ ์ด๋์๋ ์ํ๋ ๋๋ก ์ฑํ ํ ์ ์๋ค.