在我的应用程序中,我有BottomNavBar,我想在点击这BottomNavBar的项目时显示fragments

我想对这fragment中的一个使用100方法,但是当显示这fragment时不调用100

My Activity codes for set fragments to BottomNavBar items :

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()
}

My Fragment codes :

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)
        }
    }
}

Why not work setUserVisibleHint into fragment ?

推荐答案

Before you put this code you know about fragment life cycle

 override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (isVisibleToUser) {
           // post your code
        }
    }

    override fun onStart() {
        super.onStart()
        userVisibleHint = true
    }

Kotlin相关问答推荐

了解Kotlin函数

创建具有共同父类型的两种不同类型对象的列表的最有效方法是什么?

Kotlin—列出具有不同T的列表之间的操作'

"Kotlin中的表达式

Microronaut Data 4和JDbi

在构造函数中创建内部类实例时,只能使用包含类的接收器调用内部类的构造函数

如何优雅地声明一个StateFlow?

始终抛出的函数 - 具有块主体的函数中需要的返回表达式

jlink:在合并模块和 kotlin.stdlib 中打包 kotlin.*

将 SharedPreferences 中的值公开为流

如何限制 Kotlin 中的枚举?

如何将字符串格式化为电话号码kotlin算法

listOf() 返回 MutableList

RecyclerView SnapHelper无法显示第一个/最后一个元素

封闭 lambda 的隐式参数被shadowed

用于代码生成的ANTLR工具版本4.7.1与当前运行时版本4.5.3不匹配

Kotlin out-projected 类型禁止使用

Android studio 4.0 新更新版本说 Kotlin 与这个新版本不兼容

如何在 firebase 数据库中使用 kotlin 协程

在 intelliJ 元素中集成 Kotlinx 协程