티스토리 뷰
프래그먼트를 만드는 방법은 두 가지가 있다고 설명했었습니다. XML을 통해서 만들거나 코딩을 통해서 동적으로 만드는 방법이 있었는데, 이번에는 동적으로 만드는 방법을 알아봅니다.
액티비티의 하위 뷰 중에서 버튼을 이용해 프래그먼트를 생성하고 없애는 방법입니다.
바로 코드를 확인해 봅니다. 아래 코드는 액티비티 XML 파일입니다. 버튼 2개를 만들어 주고, ID가 'empty'인 뷰 하나를 추가했습니다.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context=".FragmentActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="프라그먼트 생기기"/>
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="프라그먼트 없애기"/>
<LinearLayout
android:id="@+id/empty"
android:layout_width="match_parent"
android:layout_height="200dp"
android:orientation="vertical"/>
</LinearLayout>
다음은 액티비티의 코틀린 파일입니다.
class FragmentActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_fragment)
val fragmentOne: FragmentOne = FragmentOne() //전역변수
button.setOnClickListener {
val fragmentManager: FragmentManager = supportFragmentManager
val fragmentTransaction = fragmentManager.beginTransaction() //시작
fragmentTransaction.replace(R.id.empty, fragmentOne) //바꿔주기
fragmentTransaction.commit() //끝
}
button2.setOnClickListener {
val fragmentManager = supportFragmentManager
val fragmentTransaction = fragmentManager.beginTransaction() //시작
fragmentTransaction.remove(fragmentOne) //없애기
fragmentTransaction.commit() //끝
}
}
override fun onStart() {
super.onStart()
Log.d("life_cycle", "onStart")
}
override fun onResume() {
super.onResume()
}
override fun onPause() {
super.onPause()
}
override fun onStop() {
super.onStop()
}
override fun onDestroy() {
super.onDestroy()
}
}
val fragmentOne: FragmentOne = FragmentOne() 부분을 보면, 전역 변수로서 버튼1, 2 밖에서 선언해줍니다.
버튼을 클릭하면 프래그먼트로 ID가 empty인 뷰가 바뀔 수 있도록 코딩합니다.
이렇게 프래그먼트를 동적으로 동작시키기 위해서는 프래그먼트 매니저의 도움이 필요합니다.
val fragmentManager: FragmentManager = supportFragmentManager 이런식으로 매니저의 도움을 받을 수 있도록 선언합니다.
이후에는 트랜잭션을 만들어야 합니다. 트랜잭션(Transaction)이란, 시작과 끝이 있는 작업 단위를 의미합니다.
val fragmentTransaction = fragmentManager.beginTransaction() //시작
fragmentTransaction.replace(R.id.empty, fragmentOne) // empty -> 프래그먼트로 변경
fragmentTransaction.commit() //끝
이렇게 트랜잭션에서 beginTransaction, replace, commit 메소드로 프래그먼트를 생성할 수 있습니다.
좀 전에 액티비티에서 ID가 empty였던 부분을 프래그먼트로 바꿀 때 replace 메소드를 사용했는데, replace 대신에 add(fragmentOne) 메소드 사용도 가능합니다.
commit 부분은 트랜잭션 종료를 의미하는데 commitNow( )를 써도 상관없으나 주로 commit( )을 사용합니다. commit( )은 시스템 상의 시간 순서에 따라 종료함을 의미하고, commitNow( )는 시스템 상에서 바로 종료를 의미합니다.
버튼 2도 마찬가지 입니다. 프래그먼트를 삭제하는 버튼인데, 중간에 replace 부분만 remove 또는 detach로 바꾸면 됩니다.
val fragmentTransaction = fragmentManager.beginTransaction()
fragmentTransaction.remove(fragmentOne)
fragmentTransaction.commit()
여기서 remove는 프래그먼트를 없애고 다시 생성 버튼을 누를 때 복구가 가능하지만, detach(fragmentOne)의 경우 없앤 이후 복구는 불가합니다.
프래그먼트 코틀린 파일은 이전과 동일합니다.
class FragmentOne:Fragment (){
//생략
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_first, container, false)
}
//생략
}
프래그먼트 레이아웃 파일도 동일합니다.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:background="#E91E63"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="프라그먼트"
android:textColor="#FFEB3B"
android:textSize="50dp"/>
</LinearLayout>
'Android App Coding' 카테고리의 다른 글
리소스 값 Resource Values (0) | 2021.07.09 |
---|---|
액티비티 <-> 프래그먼트 데이터 전달하기 (0) | 2021.07.08 |
프래그먼트 Fragment (0) | 2021.07.08 |
작업 관리(태스크) Task (0) | 2021.07.08 |
인텐트 Intent (0) | 2021.07.08 |
- Total
- Today
- Yesterday
- 2007년 사건사고
- 안드로이드 프로젝트
- Bmi Calculator
- lazy init
- 2021년 사건사고
- findViewById
- 상대적 레이아웃
- 애드뷰
- tabLayout
- 선형 레이아웃
- 리스트뷰
- 안드로이드 앱 만들기
- bmi 계산기 만들기
- addView
- ToDo List 앱 만들기
- RecyclerView
- 인텐트
- 안드로이드 어댑터
- 자바스크립트 배열
- 2019년 사건사고
- android adapter
- view binding
- 메소드 오버라이딩
- notifyDataSetChanged
- 미제사건
- 안드로이드 스튜디오 에러
- 대한민국 미제사건
- 리사이클러뷰
- 탭레이아웃
- 뷰 바인딩
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |