반응형
INTRO
Android 3.0(API 레벨 11)부터 Fragment라는 개념이 도입되었고,
유연성, 메모리관리, 재사용성 등의 이유로
최근 들어서는 Activity기반의 앱 보다는
Single Activity - Multi Fragment구조를 많이 사용한다.
이 포스팅은 Activity에 Fragment를 올리는 방법에 대해 설명한다.
1. fragment생성
우선 fragment를 생성한다.
fragmet클래스와 xml파일을 직접 만들어줘도 되지만, Android Studio 내장 기능을 활용하여 조금 더 편하게 생성해본다.
fragment / XML 파일이 생성된다.
이후 FirstFragment.kt 파일을 열고, 자동 생성된 코드들을 제거한 뒤 아래와 같은 형태로 남겨놓는다.
(다른 override된 메서드들은 추후 필요시 구현하면 된다)
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
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)
}
}
XML 파일은 아래와 같이 생성되어있다. 필요한대로 만들면 된다.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FirstFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_first_fragment" />
</FrameLayout>
2. Activity에 연결
소제목1 |
activity_main.xml 파일에 fragment 태그를 추가해준 후, android:name 옵션에 아래와 같이 Fragment 클래스 파일을 적어준다.
실행하면 본인이 생성한 Fragment가 보일것이다.
<?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">
<fragment
android:id="@+id/ff"
android:name="com.example.fragmenttest.FirstFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
-퍼가실 때는 출처를 꼭 같이 적어서 올려주세요!
반응형
'Dev > [Android]' 카테고리의 다른 글
[Android Kotlin] View Binding 과 Data Binding (0) | 2022.01.11 |
---|---|
[Android + Kotlin 시작하기] 간단한 App 만들어보기 - 2 (0) | 2021.12.27 |
[Android + Kotlin 시작하기] 간단한 App 만들어보기 - 1 (0) | 2021.12.27 |
[Android] SHA값 추출 (0) | 2021.05.19 |