我有一个问题,我想在 Android上的ImageView上粘贴图像,并且在一段时间后定期更改图像.表示ImageView中显示的逐个图像.我在Java的帮助下这样做但是我遇到了一些问题,即Thread没有附加什么.请
package com.ex.thread; import com.ex.thread.R; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.widget.ImageView; public class thread extends Activity implements Runnable{ /** Called when the activity is first created. */ public static Integer[] mThumbIds = { R.drawable.al1,R.drawable.al2,R.drawable.al3,R.drawable.al4, }; Thread th; ImageView iv; public void run() { for(int i=0;i<3;i++) { iv.setImageResource(mThumbIds[i]); System.out.println("Sanat Pandey"); try{ Thread.sleep(3000); }catch(Exception e) { System.out.println(e); } } } public void create() { Thread th = new Thread(new thread()); th.start(); try{ Thread.sleep(3000); }catch(Exception e) { System.out.println(e); } } @Override public void onCreate(Bundle savedInstace) { super.onCreate(savedInstace); setContentView(R.layout.main); create(); } }您不能在后台UI线程中使用UI线程.所以这个电话:
iv.setImageResource(mThumbIds[i]);
必须在主线程中完成.事实上,您可能根本不需要后台线程来获得您正在寻找的效果.你可以只做一个活动,不需要实现runnable.然后做这样的事情:
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); iv = (ImageView) findViewById(R.id.yourImageViewID); int i = 0; Runnable r = Runnable(){ public void run(){ iv.setImageResource(mThumbIds[i]); i++; if(i >= mThumbIds.length){ i = 0; } iv.postDelayed(r, 3000); //set to go off again in 3 seconds. } }; iv.postDelayed(r,3000); // set first time for 3 seconds