Activity
안드로이드에서 activity는 UI가 있는 화면을 제공하는 앱 컴포넌트이다.
-setContentView()-
- xml파일과 연결하는 역할
- Activity의 onCreate() 메서드에서는 setContentView() 메서드를 호출하고 있다.
- setContentView() 메서드는 주어진 R.layout.activity_main을 가지고 화면 구성을 한다.
- R.layout.activity_main은 /res/layout/activity_main.xml을 가리킨다.
Activity의 콜백 메서드 onCreate()
Activity를 생성할 때 onCreate를 호출하고 onCreate에서 초기화 등을 한다.
saveInstanceState
-일시적으로 삭제될 때 호출되며 이 함수를 이용해서 savedInstanceState에 현재 상태를 저장할 수 있다.
-Bundle-
- Bundle은 여러 가지의 타입의 값을 저장하는 Map 클래스
- Android에서는 Activity 간에 데이터를 주고받을 때 Bundle 클래스를 사용하여 데이터를 전송한다.
- 액티비티를 중단할 때 savedInstanceState 메서드를 호출하여 임시적으로 데이터를 저장한다.
전에 저장된 데이터가 있으면 그 데이터를 가지고 Activity를 다시 생성한다.
-fragment-
- fragment는 Activity와 유사한 구조를 가진다.
- fragment는 일반적으로 Activity의 UI의 일부로 사용되며 자체 레이아웃으로 Activity에 기여한다.
- fragment는 Activity 내에서 호스팅 되어야 한다.
- fragment는 자체적인 생명주기를 가진다.
- fragment의 생명 주기는 호스트 Activity의 생명 주기에 직접적으로 영향을 받는다.
- fragment에 대해 레이아웃을 제공하려면 반드시 onCreateView() 콜백 메서드를 구현해야 한다.
fragment의 onCreate()
- -fragment가 생성될 때 호출된다.
fragment의 onCreateView()
- -onCreate() 후에 화면을 구성할 때 호출된다.
- fragment에 맞는 UI를 그리려면 메서드에서 View를 반환해야 한다.
- R.layout.fragment_main인 xml 파일을 이용하여 화면을 그린다.
- override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_main, container, false) }
- fragment가 UI를 제공하지 않는 경우 null을 반환하면 된다.
Activity에 fragment추가
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<fragment
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:defaultNavHost="true"
app:navGraph="@navigation/nav_graph" />
</androidx.constraintlayout.widget.ConstraintLayout>