Android Studio

Android - Fragment사용하여 화면 이동 방법

내손은개발 🐾 2024. 2. 14. 22:41

1. binding 사용

앱 수준의 build.gradle에 viewBinding sync

    viewBinding{
        enable = true
    }

 

2. xml

activity_main에 FrameLayout과 버튼 2개를 생성해준다.

버튼1 -> A Fragment / 버튼2 -> B Fragment로 갈 예정

더보기

<FrameLayout
android:id="@+id/fragmentContainer"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="@id/button1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/buttonA"
android:text="A"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />

<Button
android:id="@+id/buttonB"
android:text="B"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintStart_toEndOf="@id/button1"
app:layout_constraintBottom_toBottomOf="parent"/>

 

3. MainActivity.kt

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding //binding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater) //binding
        setContentView(binding.root) //binding

        val container = binding.fragmentContainer

        binding.buttonA.setOnClickListener {
            supportFragmentManager.beginTransaction().apply {
                replace(R.id.fragmentContainer, AFragment())
                commit()
            }
        }

        binding.buttonB.setOnClickListener {
            supportFragmentManager.beginTransaction().apply {
                replace(R.id.fragmentContainer, BFragment())
                commit()
            }
        }

    }
}

 

 

4. 각 A/B Fragment.kt

class AFragment: Fragment() {

    private lateinit var binding: FragmentABinding

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentABinding.inflate(inflater)
        return binding.root
    }
}
class BFragment: Fragment() {

    private lateinit var binding: FragmentBBinding

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentBBinding.inflate(inflater)
        return binding.root
    }
}

 

 

 

결과

 

'Android Studio' 카테고리의 다른 글

Android - API 사용  (0) 2024.02.20
viewPager2 사용  (0) 2024.02.15
Android - Room  (0) 2024.02.15
Fragment 이론 정리  (0) 2024.02.15
Android 4대 컴포넌트  (0) 2024.02.14