Kok*_*and 3 android fragment android-fragments kotlin
在我的应用程序中BottomNavBar,fragments当我单击此项目时,我想要显示BottomNavBar!
对于这种设置fragments与BottomNavBar我使用的NavigationGraph成分!
我要setUserVisibleHint为此使用一种方法fragment,但是显示时fragment不调用setUserVisibleHint!
我的活动代码,用于设置fragments为BottomNavBaritems:
class HomeActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setupNavigation()
}
private fun setupNavigation() {
val navController = Navigation.findNavController(this, R.id.homePage_fragmentNavHost)
NavigationUI.setupWithNavController(homePage_bottomNavBar, navController)
}
override fun onSupportNavigateUp() = Navigation.findNavController(this, R.id.homePage_fragmentNavHost).navigateUp()
}
Run Code Online (Sandbox Code Playgroud)
我的片段代码:
class HomeDashboardFragment : Fragment(){
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home_dashboard, container, false)
}
override fun setUserVisibleHint(isVisibleToUser: Boolean) {
super.setUserVisibleHint(isVisibleToUser)
if (isVisibleToUser) {
Handler().postDelayed({ requireContext().toast("Show") }, 500)
}
}
}
Run Code Online (Sandbox Code Playgroud)
为什么不工作setUserVisibleHint进入fragment?
Ale*_*yam 17
由于不建议使用setUserVisibleHint(boolean aBoolean),对于仍想知道片段何时可见的用户,您仍然可以使用
public FragmentTransaction setMaxLifecycle(Fragment fragment, Lifecycle.State state)
Run Code Online (Sandbox Code Playgroud)
可以通过使用新的Constructor与FragmentPagerAdapter(或FragmentStatePagerAdapter)间接连接
MyFPagerAdapter(FragmentManager fm) {
super(fm ,FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
//...
}
Run Code Online (Sandbox Code Playgroud)
请注意,FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT允许适配器在内部(通过setPrimaryItem)而非setUserVisibleHint使用setMaxLifecycle。因此,在片段的实现中,您将不再需要使用
setUserVisibleHint(boolean aBoolean)
Run Code Online (Sandbox Code Playgroud)
但是,onResume()导致现在仅针对可见片段调用onResume()。其余的仍然可以访问onCreateView()。
直接的方法是在添加或切换片段时使用带有FragmentTransaction的setMaxLifeCycle,然后
setMaxLifecycle(fragment, Lifecycle.State.STARTED);
Run Code Online (Sandbox Code Playgroud)
等价
setUserVisibleHint(false);
Run Code Online (Sandbox Code Playgroud)
和
setMaxLifecycle(fragment, Lifecycle.State.RESUMED);
Run Code Online (Sandbox Code Playgroud)
相当于
setUserVisibleHint(true);
Run Code Online (Sandbox Code Playgroud)
然后再次使用Fragment的onResume()回调进行监听
在放置此代码之前,您需要了解片段生命周期
override fun setUserVisibleHint(isVisibleToUser: Boolean) {
super.setUserVisibleHint(isVisibleToUser)
if (isVisibleToUser) {
// post your code
}
}
override fun onStart() {
super.onStart()
userVisibleHint = true
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4022 次 |
| 最近记录: |