6-1. 화면을 구성하는 방법

StrayCat·2022년 10월 4일
0

액티비티-뷰 구조

  • 앱을 구성하는 컴포넌트 4가지 ( 액티비티, 리시버, 프로바이더, 서비스 ) 중에서 화면을 출력하는 컴포넌트는 액티비티이다.
  • 액티비티는 화면을 출력하는 컴포넌트이지만, 그 자체가 화면은 아니다.
  • 화면에 내용을 표시하려면 뷰(View) 클래스를 이용해야한다. ( ex) TextView, ImageView, .. )

액티비티에서 뷰로 화면을 구성하는 법은 2가지이다.

  1. 액티비티 코드로 작성
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val name = TextView(this).apply{
            typeface = Typeface.DEFAULT_BOLD
            text = "Hello"
        }

        val image = ImageView(this).also{
            it.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_launcher_foreground))
        }

        val layout = LinearLayout(this).apply {
            orientation = LinearLayout.VERTICAL
            gravity = Gravity.CENTER

            addView(name, WRAP_CONTENT, WRAP_CONTENT)
            addView(image, WRAP_CONTENT, WRAP_CONTENT)

        }

        setContentView(layout)
    }
}
  1. 레이아웃 XML 파일로 작성
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello"
        android:textStyle="bold"/>

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher_foreground">
        
    </ImageView>
</androidx.appcompat.widget.LinearLayoutCompat>
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)
    }
}

화면구성은 XML파일로 분리하고 액티비티에서는 네트워킹, 데이터 관리, 사용자 이벤트 처리 위주로 하는것이 효율적이다.

0개의 댓글