1. 정의
- 액티비티 위에서 동작하는 모듈화된 사용자 인터페이스
- 여러 개의 프래그먼트를 하나의 액티비티에 조합해 사용 (프래그먼트 재사용 가능)
- 액티비티와 분리되어 독립적 동작
2. 액티비티 vs 프래그먼트
1) Activity : 인텐트를 통해 액티비티간 데이터 전달
2) Fragment : 메소드로 프래그먼트간 데이터 전달
- Activity 적게 사용 가능, 복잡도 줄임
- 재사용 할 수 있는 레이아웃 분리해서 관리 가능
- 자원 이용량 적어 속도 빠름
3. 프래그먼트 파일
xml 파일
화면의 표시될 뷰 정의
Fragment
class FirstFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_first, container, false)
}
4. 액티비티의 레이아웃 파일에 정적으로 프래그먼트 추가
- 프래그먼트를 액티비티의 레이아웃 파일 안에서 선언
- 각 프래그먼트에서는 고유한 식별자 필요
- 고유한 Id와 함께 android:id 속성 제공
- 고유한 문자열과 함께 android:tag 속성 제공
- 시스템은 컨테이너뷰의 Id 사용
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<fragment
android:name="com.skmns.fragmentbasic.FirstFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/fragment" />
</LinearLayout>
5. Kotlin 코드에서 동적으로 프래그먼트 추가
supportFragmentManager.commit {
replace(R.id.frameLayout, FirstFragment())
setReorderingAllowed(true)
addToBackStack("")
}
- supportFragmentManager : 사용자와 상호작용, Fragment 추가하거나 삭제해주는 매니저
- replace : 어느 프레임 레이아웃, 어떤 프래그먼트 띄울 것인가
- setReorderingAllowed : 애니메이션과 전환이 올바르게 작동하도록 관련된 프래그먼트 상태 변경 최적화
- addToBackStack : 뒤로 가기 버튼 클릭 시 다음 액션 (이전 fragment or 앱 종료)
프래그먼트 예제
fragment_first.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:background="#F19B9B"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="프v래그먼트 1"
android:textAllCaps="false"
android:textSize="40sp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
fragment_second.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:background="#C785D3"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="프래그먼트 2"
android:textAllCaps="false"
android:textSize="40sp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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">
<FrameLayout
android:id="@+id/frameLayout"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp"
app:layout_constraintBottom_toTopOf="@+id/fragment1_btn"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</FrameLayout>
<Button
android:id="@+id/fragment1_btn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Frag1"
android:textAllCaps="false"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/fragment2_btn"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/frameLayout" />
<Button
android:id="@+id/fragment2_btn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Frag2"
android:textAllCaps="false"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/fragment1_btn"
app:layout_constraintTop_toBottomOf="@+id/frameLayout" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity
class MainActivity : AppCompatActivity() {
private lateinit var binding : ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.apply {
fragment1Btn.setOnClickListener{
setFragment(FirstFragment())
}
fragment2Btn.setOnClickListener {
setFragment(SecondFragment())
}
}
// 프로그램 시작할 때 맨 처음 화면
setFragment(FirstFragment())
}
private fun setFragment(frag : Fragment) {
supportFragmentManager.commit {
replace(R.id.frameLayout, frag)
setReorderingAllowed(true)
addToBackStack("")
}
}
}
'Android' 카테고리의 다른 글
어댑터뷰 (0) | 2023.08.29 |
---|---|
Dialog (0) | 2023.08.25 |
뷰 바인딩 (0) | 2023.08.24 |
RecyclerView에 데이터 추가하기 (Fragment, ViewPager2) (1) | 2023.08.23 |
View와 ViewGroup (2) | 2023.08.10 |