diff --git a/android/src/main/java/com/swmansion/rnscreens/ScreenStackFragment.kt b/android/src/main/java/com/swmansion/rnscreens/ScreenStackFragment.kt index 725bcf879a..358e200fed 100644 --- a/android/src/main/java/com/swmansion/rnscreens/ScreenStackFragment.kt +++ b/android/src/main/java/com/swmansion/rnscreens/ScreenStackFragment.kt @@ -19,6 +19,7 @@ import androidx.coordinatorlayout.widget.CoordinatorLayout import com.facebook.react.uimanager.PixelUtil import com.google.android.material.appbar.AppBarLayout import com.google.android.material.appbar.AppBarLayout.ScrollingViewBehavior +import com.swmansion.rnscreens.utils.DeviceUtils class ScreenStackFragment : ScreenFragment, ScreenStackFragmentWrapper { private var mAppBarLayout: AppBarLayout? = null @@ -26,6 +27,8 @@ class ScreenStackFragment : ScreenFragment, ScreenStackFragmentWrapper { private var mShadowHidden = false private var mIsTranslucent = false + private var mLastFocusedChild: View? = null + var searchView: CustomSearchView? = null var onSearchViewCreate: ((searchView: CustomSearchView) -> Unit)? = null @@ -89,6 +92,11 @@ class ScreenStackFragment : ScreenFragment, ScreenStackFragmentWrapper { } } + override fun onStart() { + mLastFocusedChild?.requestFocus() + super.onStart() + } + override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, @@ -123,6 +131,13 @@ class ScreenStackFragment : ScreenFragment, ScreenStackFragmentWrapper { return view } + override fun onStop() { + if (DeviceUtils.isPlatformAndroidTV(context)) + mLastFocusedChild = findLastFocusedChild() + + super.onStop() + } + override fun onPrepareOptionsMenu(menu: Menu) { updateToolbarMenu(menu) return super.onPrepareOptionsMenu(menu) @@ -163,6 +178,16 @@ class ScreenStackFragment : ScreenFragment, ScreenStackFragmentWrapper { } } + private fun findLastFocusedChild(): View? { + var view: View? = screen + while (view != null) { + if (view.isFocused) return view + view = if (view is ViewGroup) view.focusedChild else null + } + + return null + } + override fun canNavigateBack(): Boolean { val container: ScreenContainer? = screen.container check(container is ScreenStack) { "ScreenStackFragment added into a non-stack container" } diff --git a/android/src/main/java/com/swmansion/rnscreens/utils/DeviceUtils.kt b/android/src/main/java/com/swmansion/rnscreens/utils/DeviceUtils.kt new file mode 100644 index 0000000000..57ddaaa5d3 --- /dev/null +++ b/android/src/main/java/com/swmansion/rnscreens/utils/DeviceUtils.kt @@ -0,0 +1,12 @@ +package com.swmansion.rnscreens.utils + +import android.content.Context +import android.content.pm.PackageManager + +object DeviceUtils { + + fun isPlatformAndroidTV(context: Context?): Boolean { + return context?.packageManager?.hasSystemFeature(PackageManager.FEATURE_LEANBACK) == true + } + +}