2011-02-28 68 views
0

我正在制作一个应用程序,我在不断调整布局背景以像翻转背景一样,我使用Activity.runOnUiThread()函数实现背景更改,因为它是UI功能,使用Thread().sleep()等待2秒,但该应用程序只显示我在最后提到的布局颜色。连续更改布局背景

package com.tutorial.flasher; 

import android.app.Activity; 
import android.graphics.Color; 
import android.os.Bundle; 
//import android.os.SystemClock; 
//import android.os.SystemClock; 
import android.widget.LinearLayout; 


public class flasher extends Activity { 
    /** Called when the activity is first created. */ 
    LinearLayout llaLayout; 
    Thread th = new Thread("ThreadOne"); 
    Activity _activity = new Activity(); 


@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    llaLayout = (LinearLayout)findViewById(R.id.layo); 



    Thread t1 = new Thread(new Runnable() { 

     public void run() { 
      try 
      { 
       Thread.sleep(2000); 
      } 
      catch (Exception e) { 
       // TODO: handle exception 
      } 
     } 
    }); 

    t1.start(); 
    t1.run(); 
    t1.stop(); 


    _activity.runOnUiThread(new Runnable(){ 
     public void run(){ 
      llaLayout.setBackgroundColor(Color.parseColor("#00FF00")); 

     } 
    }); 
    //t1.currentThread(); 
    t1.start(); 
    t1.run(); 
    t1.stop(); 

    _activity.runOnUiThread(new Runnable(){ 
     public void run(){ 
           //Color BLUE of layout 
      llaLayout.setBackgroundColor(Color.parseColor("#0000FF")); 

     } 
    }); 


} 

}

无论是用户界面的变化和线程凝视将在循环中发生(未示出),但仍然在应用程序改变布局颜色只有一次。 谢谢, 希德

回答

3
  1. 你不应该new活动,活动由Android系统的建立。
  2. 致电Thread.start将启动线程,不需要拨打Thread.run

Activity.runOnUiThread也许不是最好的方法来存档这个,试试Handler。下面是示例代码:

public class BroadcastActivity extends Activity { 

    public static final int CHANGE_BGCOLOR = 1; 

    private LinearLayout llaLayout; 

    private Handler handler = new Handler() { 
     public void handleMessage(android.os.Message msg) { 
      if (msg.what == 1) { 
       String color = (String) msg.obj; 
       llaLayout.setBackgroundColor(Color.parseColor(color)); 
       String nextColor = ""; // Next background color; 
       Message m = obtainMessage(CHANGE_BGCOLOR, nextColor); 
       sendMessageDelayed(m, 200); 
      } 
     } 
    }; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     llaLayout = (LinearLayout)findViewById(R.id.layo); 
     String nextColor = ""; // Next background color; 
     Message m = handler.obtainMessage(CHANGE_BGCOLOR, nextColor); 
     handler.sendMessageDelayed(m, 200); 
    } 
} 
+0

感谢您的回答托尼,对不起,我花了几天试试答案,我仍然在努力获得重复的方式工作的功能,你有如何的任何建议我可以得到那个工作吗?谢谢。 – Sid 2011-03-02 22:22:14

+0

这是一个关于定时UI更新的教程,希望它能提供帮助。 http://developer.android.com/resources/articles/timed-ui-updates.html – Tony 2011-03-07 13:39:25