After ADS ’19 - Fragments: 과거, 현재, 그리고 미래

AndroidDevSummit 세션 내용을 간단히 정리해봅니다.

SOUP
SOUP
Nov 5 · 6 min read
Fragments: Past, Present, and Future

과거

  • Fragments = Micro activities
  • “Activity가 할 수 있는 것은 Fragment도 할 수 있다.”

현재

대표적으로 4가지의 신규 API가 추가되었다. (1.2.0 기준)

  • Using FragmentScenario, Test Fragments!
    : Fragment를 테스트할 수 있게 변경된다.
@Test
fun testEventFragment() {
val scenario = launchFragmentInContainer<MyFragment>()
onView(withId(R.id.refresh)).perform(click())
scenario.onFragment { fragment ->
// Check that the fragment handled the click correctly.
}
}
@Test
fun testEventMoveToCreatedFragment() {
val scenario = launchFragmentInContainer<MyFragment>()
scenario.moveToState(State.CREATED)
}
@Test
fun testEventFragment() {
val scenario = launchFragmentInContainer<MyFragment>()
scenario.recreate()
}
  • Using FragmentFactory, Create instance and mocking!
    : Fragment를 생성하는 방법을 변경하여, Mocking 할 수 있게 된다.
private class MyFactory() : FragmentFactory() {
override fun instantiate(
classLoader: ClassLoader,
className: String
) = when (className) {
MyFragment::class.java.name -> MyFragment()
else -> super.instantiate(classLoader, className)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
supportFragmentManager.fragmentFactory = MyFactory()
super.onCreate(savedInstanceState)
}
// Add a new Fragment via its class name
supportFragmentManager.commit {
add<MyFragment>(R.id.container)
}
// Create a FragmentScenario using a custom FragmentFactory
val scenario = launchFragmentInContainer<MyFragment>(
factory = MockFactory()
)
  • Using FragmentContainerView, Replace <fragment> Tag!
    : XML에서 선언하는 형태가 바뀐다.
<!-- Same as doing an add() in onCreate -->
<androidx.fragment.app.FragmentContainerView
class="com.example.MyFragment"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
  • Using OnBackPressedDispatcher, Handle Back events!
    : Fragment에서 Back 키를 제어할 수 있게 된다.
val dispatcher by lazy { requireActivity().onBackPressedDispatcher }
lateinit var callback: OnBackPressedCallback
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
callback = dispatcher.addCallback(this) {
showConfirmDialog()
}
}
private fun onConfirm() {
callback.enabled = false
dispatcher.onBackPressed()
}
  • APIs for Arch Components
    : 이외에도 Arch Components와 연관된 API가 추가된다.
    (ViewModel, Lifecycle)
// Make it easy to get an instance of your ViewModel
val viewModel : MyViewModel by viewModels()
val navGraphViewModel : MyViewModel by navGraphViewModels(R.id.main)
val activityViewModel : MyViewModel by activityViewModels()
// Only let onResume() be called on the current Fragment
class MyAdapter :
FragmentPagerAdapter(BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT)

미래

Navigation Components 관련 이슈로 등록되어 있던 내용이 많았다.

  • Multiple back stacks 지원
    : Tab UX에서 필요한 Multiple BackStack을 지원할 예정이다.
  • Fragment 간 Results 전달 기능 지원 👏
    : startActivityForResult()에 대응되는 기능을 지원할 예정이다.
  • Fragment Lifecycle(s) 단일화 🤔
    : Fragment는 Fragment와 View 각각 Lifecycle을 갖는데,
    이를 통합하여 단일 Lifecycle로 변경할 예정이다.
    FragmentActivity 레벨에서 API 변경이 있을 것 같다.

내년에 변화될 Fragment를 기대해본다.

    SOUP

    Written by

    SOUP

    Android Developer in South Korea.

    Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
    Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
    Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade