- 한 액티비티에서 여러 프래그먼트를 보여줄 수 있음
- 여러 액티비티에서 하나의 프래그먼트 재활용 가능
액티비티 생명주기 흐름도
- onCreate()함수 호출 👉 액티비티가 생성된 상태
- 멈춰진 상태 👉 onDestroy()함수 호출 👉 앱 종료
fun settingButton () {
//xml 파일에서 추가한 버튼 객체를 변수로 만듦
//findViewById()함수는 뷰의 id값을 인수로 받음
val button = findViewById<Button>(R.id.button)
//버튼일 클릭되었을 때 행동을 SetOnClickListener()에 지정
button.setOnClickListener {
//intent 변수 생성 후 인턴드 객체 생성
//Intent(현재 객체, 이동할 목적지)
val intent = Intent(this, SubActivity::class.java)
// startActivity() 함수는 방금 만든 인텐트 객체를 인수로 받아 새로운 액티비티 시작
startActivity(intent)
}
}
👉 전체 작동 코드
MainActivity.ktimport android.content.Intent import android.os.Bundle import android.widget.Button import androidx.activity.ComponentActivity class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) settingButton() } fun settingButton () { val button = findViewById<Button>(R.id.button) button.setOnClickListener { val intent = Intent(this, SubActivity::class.java) startActivity(intent) } } }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"> <TextView android:id="@+id/test1" android:text="Hi" android:textSize="35dp" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintTop_toTopOf="parent"/> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Go to SubActivity" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/test1" /> </androidx.constraintlayout.widget.ConstraintLayout>SubActivity.kt
import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class SubActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_sub) } }activity_sub.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=".SubActivity"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Sub Activity" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
프래그먼트의 생명주기
class RedFragment : Fragment() {
override fun onCreateView( // 프래그먼트 레이아웃을 연결할 때 사용하는 콜백 함수
// 뷰 생성 객체
inflater: LayoutInflater,
// 생성할 뷰(자식 뷰)가 들어갈 부모 뷰
container: ViewGroup?,
// 이전 프래그먼트 객체에서 전달된 데이터(번들)
savedInstanceState: Bundle?
): View? {
// 인수로 받는 inflater를 통해 프래그먼트의 레이아웃 지정
// inflate(리소스 참조값, 부모 뷰, attachToRoot)
//attachToRoot: 지금 즉시 부모 뷰에 뷰를 추가할 것인지 나중에 추가할 것인지
return inflater.inflate(R.layout.fragment_red, container, false);
}
}
TwoColorActivity.kt
fun settingButtons() {
val redButton = findViewById<Button>(R.id.button_red_fragment)
val blueButton = findViewById<Button>(R.id.button_blue_fragment)
redButton.setOnClickListener {
// supportFragmentManager.beginTransaction()을 호출해 프래그먼트 트랜잭션 클래스의 객체 생성
// 프래그먼트 트랜잭션: 프래그먼트 추가, 삭제, 기존 프래그먼트와 교체 후 백스택에 추가 등을 수행
val fragmentTransaction = supportFragmentManager.beginTransaction()
// 트랜잭션에서 수행할 활동 정의
// replace()로 기존의 프래그먼트를 새로운 프래그먼트로 교체
//replace(프래그먼트를 넣는 프레임 레아이웃 id, 새로운 프래그먼트 객체)
fragmentTransaction.replace(R.id.framelayout,RedFragment())
// 트랜잭션 이후 반드시 commit() 함수 호출
fragmentTransaction.commit()
}
}
전체 코드
MainActivity.kt
import android.content.Intent import android.os.Bundle import android.widget.Button import androidx.activity.ComponentActivity class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) settingButton() } fun settingButton () { //xml 파일에서 추가한 버튼 객체를 변수로 만듦 //findViewById()함수는 뷰의 id값을 인수로 받음 val sub_button = findViewById<Button>(R.id.sub_button) val two_button = findViewById<Button>(R.id.two_button) //버튼일 클릭되었을 때 행동을 SetOnClickListener()에 지정 sub_button.setOnClickListener { //intent 변수 생성 후 인턴드 객체 생성 //Intent(현재 객체, 이동할 목적지) val intent = Intent(this, SubActivity::class.java) // startActivity() 함수는 방금 만든 인텐트 객체를 인수로 받아 새로운 액티비티 시작 startActivity(intent) } two_button.setOnClickListener { val intent = Intent(this, TwoColorActivity::class.java) startActivity(intent) } } }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"> <TextView android:id="@+id/test1" android:text="Hi" android:textSize="35dp" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintTop_toTopOf="parent"/> <Button android:id="@+id/sub_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Go to SubActivity" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/test1" /> <Button android:id="@+id/two_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Go to two fragment" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/sub_button" /> </androidx.constraintlayout.widget.ConstraintLayout>TwoColorActivity.kt
import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button class TwoColorActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_two_color) settingButtons() } fun settingButtons() { val redButton = findViewById<Button>(R.id.button_red_fragment) val blueButton = findViewById<Button>(R.id.button_blue_fragment) redButton.setOnClickListener { // supportFragmentManager.beginTransaction()을 호출해 프래그먼트 트랜잭션 클래스의 객체 생성 // 프래그먼트 트랜잭션: 프래그먼트 추가, 삭제, 기존 프래그먼트와 교체 후 백스택에 추가 등을 수행 val fragmentTransaction = supportFragmentManager.beginTransaction() // 트랜잭션에서 수행할 활동 정의 // replace()로 기존의 프래그먼트를 새로운 프래그먼트로 교체 //replace(프래그먼트를 넣는 프레임 레아이웃 id, 새로운 프래그먼트 객체) fragmentTransaction.replace(R.id.framelayout,RedFragment()) // 트랜잭션 이후 반드시 commit() 함수 호출 fragmentTransaction.commit() } blueButton.setOnClickListener { val fragmentTransaction = supportFragmentManager.beginTransaction() fragmentTransaction.replace(R.id.framelayout, BlueFragment()) fragmentTransaction.commit() } } }activity_two_color.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=".TwoColorActivity"> <FrameLayout android:id="@+id/framelayout" android:layout_width="match_parent" android:layout_height="300dp" android:background="#FFEB3B" app:layout_constraintTop_toTopOf="parent"/> <Button android:id="@+id/button_red_fragment" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_constraintBottom_toBottomOf="parent" android:layout_margin="10dp" android:text="Red Fragment"/> <Button android:id="@+id/button_blue_fragment" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_constraintBottom_toTopOf="@+id/button_red_fragment" android:layout_margin="10dp" android:text="Blue Fragment"/> </androidx.constraintlayout.widget.ConstraintLayout>BlueFragment.kt
import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment class BlueFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_blue, container, false); } }fragment_blue.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:layout_height="match_parent"> <FrameLayout android:id="@+id/framelayout" android:layout_width="match_parent" android:layout_height="300dp" android:background="#03A9F4" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>fragment_red.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:layout_height="match_parent"> <FrameLayout android:id="@+id/framelayout" android:layout_width="match_parent" android:layout_height="300dp" android:background="#F44336" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
