android,无法使用计时器

时间:2011-08-22 13:28:14

标签: android timer timertask

我想每秒更改一次帧布局的背景图像。对于这个任务,我使用计时器和timertask类,但它似乎不起作用,因为初始背景永远不会改变,我测试以下代码的pyhsical设备异常终止。

    FrameLayout fl;
List<Integer> myList;
int i = 0;
TimerTask myTimerTask = new TimerTask()
{
    public void run()
    {
        fl.setBackgroundResource(myList.get(i));
        i++;
    }
};


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    myList = new ArrayList<Integer>();
    myList.add(R.drawable.square1);
    myList.add(R.drawable.square2);
    myList.add(R.drawable.square3);
    myList.add(R.drawable.square4);
    myList.add(R.drawable.square5);
    myList.add(R.drawable.square6);
    myList.add(R.drawable.square7);
    myList.add(R.drawable.square8);
    myList.add(R.drawable.square9);
    myList.add(R.drawable.square10);
    myList.add(R.drawable.square11);
    myList.add(R.drawable.square12);



    fl = (FrameLayout)findViewById(R.id.frameLayout1);

    long delay = 1000;
    long period = 1000;

    Timer t = new Timer();
    t.schedule(myTimerTask,delay,period);


}

我哪里失败了? ^^ 提前感谢您的时间。

3 个答案:

答案 0 :(得分:0)

您应在设置新的后台资源后调用invalidate()

答案 1 :(得分:0)

您无法像非定时器一样从非UI线程访问视图。您需要有一个处理程序来更新视图并获取计时器以向其发送消息。你需要阻止我走出界限,例如:

TimerTask myTimerTask = new TimerTask() {
    public void run() {
        Message m = Message.obtain();
        m.what = i;
        myUpdateHandler.sendMessage(m);
        i++;
        if (i >= myList.size())
            i = 0;
    }
};

Handler myUpdateHandler = new Handler() {
    /** Gets called on every message that is received */
    @Override
    public void handleMessage(Message msg) {
        fl.setBackgroundResource(myList.get(msg.what));

    }
};

答案 2 :(得分:-1)

嗯,你的代码有几个问题。 从您的代码中,它不清楚“fi”的初始化位置,是否在调用定时器回调之前?后? int“i”的目的是什么?不应该是班级成员吗? 您必须在活动的onDestroy上停止计时器,否则在访问框架布局时可能会出现一些不良行为。

无论如何,尝试从onCreate运行以下内容:

final FrameLayout fl = (FrameLayout)findViewById(R.id.frameLayout1); // You must have final here
final List<Integer> myList = <get it from where you need to>
int i = 0; // What is the purpose of this int? it passed by value to the callback - are you sure it is needed?
TimerTask myTimerTask = new TimerTask()
{
    public void run()
    {
        fl.setBackgroundResource(myList.get(i));
        i++; // Shouldn't it be a class member?
    }
};