子线程中更新UI的几种方式

一、主线程申请成功后子线程申请

val textView:TextView = findViewById<TextView>(R.id.textView)
textView.setOnClickListener{
    textView.text = "Main"
    thread{
        textView.text = "${Thread.currentThread().name}"
    }
}

二、在子线程中创建ViewRootImpl

thread{
    Looper.prepare()
    val button = Button(this)
    windowManager.addView(button,WindowManager.LayoutParams())
    button.setOnClickListener{
        button.text="${Thread.currentThread().name}"
    }
    Looper.loop()
}

三、利用硬件加速机制绕开requestLayout()
在硬件加速支持下,如果控件只是执行了invalidate(),而没有触发requestLayout(),是不会触发ViewRootImpl#checkThread()的


ViewGroup.png

四、SurfaceView
Android中有一个控件SurfaceView,可以通过holder获得Canvas对象,可以直接在子线程中更新UI

val surface :SurfaceView! =findViewById<SurfaceView>(R.id.surface)
surface.holder.addCallback(object :SurfaceHolder.Callback {
    override fun surfacedreated(holder:SurfaceHolder){
        thread {
            while(!destroved){
                val canvas :Canvas! = holder.lockCanvas()
                val random = Random()
                val r:Int =random.nextInt( bound: 255)
                val g:Int =random.nextInt( bound: 255)
                val b:Int = random.nextInt( bound: 255)
                canvas.drawColor(Color.rgb(r,g,b))
                holder.unlockCanvasAndPost(canvas)
                SystemClock.sleep( ms:500)
             } 
         }
    }

    override fun surfaceDestroyed(holder: SurfaceHolder?){
        destroved = true
    }

    override fun surfaceChanged(
        holder: SurfaceHolder?,
        format: Int
        width: Int
        height: Int
    ){

    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容