为了账号安全,请及时绑定邮箱和手机立即绑定

Android kotlin - BottomNavigationView 在 TimerTask

Android kotlin - BottomNavigationView 在 TimerTask

郎朗坤 2021-11-17 17:17:53
这是有效的代码: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
查看完整描述

1 回答

?
慕勒3428872

TA贡献1848条经验 获得超6个赞

您不能直接在另一个线程上更改视图属性,只能在主线程上更改。


val timerTask = object : TimerTask() {

    override fun run() {

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


        menuView.post{


      QBadgeView(this@Stackoverflow).bindTarget(menuView!!.getChildAt(3)).badgeNumber = 7


        }

    }


查看完整回答
反对 回复 2021-11-17
  • 1 回答
  • 0 关注
  • 208 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信