Upgrade to Pro — share decks privately, control downloads, hide ads and more …

最新のFragment事情 / Fragment new features

star_zero
November 21, 2019

最新のFragment事情 / Fragment new features

star_zero

November 21, 2019
Tweet

More Decks by star_zero

Other Decks in Programming

Transcript

  1. OnBackPressedDispatcher class SampleFragment : Fragment() { private val callback =

    object : OnBackPressedCallback(true) { override fun handleOnBackPressed() { // バックキーが押されたとき... } } override fun onAttach(context: Context) { super.onAttach(context) requireActivity().onBackPressedDispatcher .addCallback(this, callback) } }
  2. OnBackPressedDispatcher class SampleFragment : Fragment() { // ... fun someFunction()

    { callback.isEnabled = false requireActivity().onBackPressedDispatcher.onBackPressed() } }
  3. OnBackPressedDispatcher class MainActivity : AppCompatActivity() { override fun onBackPressed() {

    // FragmentのhandleOnBackPressedの後に呼び出される if (onBackPressedDispatcher.hasEnabledCallbacks()) { // Fragmentのバックキー制御が有効 } else { // Fragmentのバックキー制御が無効 } } }
  4. FragmentFactory class SampleFactory: FragmentFactory() { override fun instantiate( classLoader: ClassLoader,

    className: String ): Fragment { return when (className) { SampleFragment::class.java.name -> SampleFragment("ABC") else -> super.instantiate(classLoader, className) } } }
  5. FragmentFactory class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?)

    { supportFragmentManager.fragmentFactory = SampleFactory() super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // fragment-ktx supportFragmentManager.commit { add<SampleFragment>(R.id.container) } } }
  6. FragmentFactory @RunWith(AndroidJUnit4::class) class SampleFragmentTest { @Test fun textSample() { val

    mockFactory = MockFactory() val scenario = launchFragmentInContainer<SampleFragment>( factory = mockFactory ) onView(withId(R.id.text)).check(matches(withText("Hello World!"))) } }
  7. RESUME_ONLY_CURRENT_FRAGMENT class SampleAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) { // 以前の挙動にしたい場合は

    BEHAVIOR_SET_USER_VISIBLE_HINT override fun getItem(position: Int): Fragment { // ... } override fun getCount(): Int { // ... } }
  8. fragment-ktx supportFragmentManager.commit { add<SampleFragment>(R.id.container) } val viewModel: SampleViewModel by viewModels()

    val viewModel: SampleViewModel by activityViewModels() val viewModel: SampleViewModel by viewModels { viewModelFactory }