Android kotlin - BottomNavigationView 在 TimerTask

这是有效的代码:


class Stackoverflow : AppCompatActivity() {


    private var menuView: BottomNavigationMenuView? = null

    private var mBottomNavigationView: BottomNavigationView? = null

    private var newmsgTimer: Timer? = null



    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_home)



        mBottomNavigationView = findViewById<View>(R.id.bottom_navigation) as BottomNavigationView

        menuView = mBottomNavigationView!!.getChildAt(0) as BottomNavigationMenuView



        mBottomNavigationView!!.setOnNavigationItemSelectedListener { item ->

            when (item.itemId) {

                R.id.nav_voting -> {


                }

                R.id.nav_search -> {


                }

            }

            return@setOnNavigationItemSelectedListener true

        }


        newmsg()

    }




    private fun newmsg(){

        QBadgeView(this@Stackoverflow).bindTarget(menuView!!.getChildAt(3)).badgeNumber = 7 // IT WORKS HERE


        newmsgTimer = Timer()


        val timerTask = object:TimerTask() {

            override fun run() {

                Log.d("letsSee", "PIKABOO") // it's getting printed


            }

        }


        newmsgTimer!!.schedule(timerTask, 0, 60000)

    }

}


那么它不起作用。


我不知道这个错误是关于什么的:


java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getVisibility()' on a null object reference

        at android.support.design.internal.BottomNavigationMenuView.onMeasure(BottomNavigationMenuView.java:145)

任何想法如何使它在 TimeTask 中工作?提前致谢


编辑:


再次运行后,我也收到此错误:


FATAL EXCEPTION: Timer-1

    Process: com.exmpl.exmpl, PID: 9978

    android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

忽略这一点:需要添加更多单词blabla


郎朗坤
浏览 209回答 1
1回答

慕勒3428872

您不能直接在另一个线程上更改视图属性,只能在主线程上更改。val timerTask = object : TimerTask() {&nbsp; &nbsp; override fun run() {&nbsp; &nbsp; &nbsp; &nbsp; Log.d("letsSee", "PIKABOO") // it's getting printed&nbsp; &nbsp; &nbsp; &nbsp; menuView.post{&nbsp; &nbsp; &nbsp; QBadgeView(this@Stackoverflow).bindTarget(menuView!!.getChildAt(3)).badgeNumber = 7&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java