当前位置: 移动技术网 > IT编程>移动开发>Android > Android 实现界面刷新的几种方法

Android 实现界面刷新的几种方法

2019年07月24日  | 移动技术网IT编程  | 我要评论

2016年国考,欧洲bt,渝简称

android 界面刷新

 android提供了invalidate方法实现界面刷新,但是invalidate不能直接在线程中调用,因为他是违背了单线程模型:android ui操作并不是线程安全的,并且这些操作必须在ui线程中调用。

android程序中可以使用的界面刷新方法有两种,分别是利用handler和利用postinvalidate()来实现在线程中刷新界面。

利用handler刷新界面

实例化一个handler对象,并重写handlemessage方法调用invalidate()实现界面刷新;而在线程中通过sendmessage发送界面更新消息。


    // 在oncreate()中开启线程

    new thread(new gamethread()).start();、

 

    // 实例化一个handler

    handler myhandler  = new handler()

    {

       //接收到消息后处理

       public void handlemessage(message msg)

       {

           switch (msg.what)

           {

           case activity01.refresh:

              mgameview.invalidate();    //刷新界面

              break;

           }

           super.handlemessage(msg);

       }         

    };

 

    class gamethread implements runnable

    {

       public void run()

       {

           while (!thread.currentthread().isinterrupted())

           {

              message message = new message();

              message.what = activity01.refresh;

              //发送消息

              activity01.this.myhandler.sendmessage(message);

              try

              {

                  thread.sleep(100);

              }

              catch (interruptedexception e)

              {

                  thread.currentthread().interrupt();

              }

           }

       }

    }

使用postinvalidate()刷新界面

使用postinvalidate则比较简单,不需要handler,直接在线程中调用postinvalidate即可。

 class gamethread implements runnable

    {

       public void run()

       {

           while (!thread.currentthread().isinterrupted())

           {

              try

              {

                  thread.sleep(100);

              }

              catch (interruptedexception e)

              {

                  thread.currentthread().interrupt();

              }

              //使用postinvalidate可以直接在线程中更新界面

              mgameview.postinvalidate();

           }

       }

    }

 

参考:

android应用开发揭秘

android文档

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网