0

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

    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);


}

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

4

3 回答 3

0

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

于 2011-08-22T14:43:33.940 回答
0

您无法从非 UI 线程(如计时器)访问视图。您需要有一个处理程序来更新视图并让计时器向其发送消息。你需要阻止 i 越界,比如:

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));

    }
};

.

于 2011-08-22T14:56:08.740 回答
-1

好吧,你的代码有几个问题。从您的代码中不清楚“fi”的初始化位置,是在调用计时器回调之前吗?后?int“i”的目的是什么?不应该是班级成员吗?您必须在 Activity 的 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?
    }
};
于 2011-08-22T13:39:42.337 回答