2015-04-18 69 views
0

我制作了一个数组,其中包含int中的所有图像,并且我希望每隔3秒在imageView中更改这些图像,我尝试了所有可找到的解决方案,但显示出一些错误,我无法弄清楚。如何在imageview中每n秒钟更改一次图像

的java文件(home.java)

/** 
* Created by sukhvir on 17/04/2015. 
*/ 
public class home extends android.support.v4.app.Fragment { 

    ImageView MyImageView; 
    int[] imageArray = { R.drawable.image1, R.drawable.image2, R.drawable.image3, R.drawable.image4, R.drawable.image5 }; 

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     /** 
     * Inflate the layout for this fragment 
     */ 
     return inflater.inflate(R.layout.home, container, false); 
    } 
} 

XML文件(home.xml)

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <ImageView 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:id="@+id/imageView" 
     android:layout_gravity="center_horizontal" /> 
</LinearLayout> 
+0

Yon可以简单地使用Thread/Timer/CountDownTimer在每秒钟更改图像。 – SilentKiller

回答

3

最好的选择来实现你的要求是你应该使用Timer来改变图像每3秒如下。

// Declare globally 
private int position = -1; 

/** 
* This timer will call each of the seconds. 
*/ 
Timer mTimer = new Timer(); 
mTimer.schedule(new TimerTask() { 
    @Override 
    public void run() { 
     // As timer is not a Main/UI thread need to do all UI task on runOnUiThread 
     getActivity().runOnUiThread(new Runnable() { 
      @Override 
      public void run() { 
        // increase your position so new image will show 
       position++; 
       // check whether position increased to length then set it to 0 
       // so it will show images in circuler 
       if (position >= imageArray.length) 
        position = 0; 
       // Set Image 
       MyImageView.setImageResource(imageArray[position]); 
      } 
     }); 
    } 
}, 0, 3000); 
// where 0 is for start now and 3000 (3 second) is for interval to change image as you mentioned in question 
+0

我得到的位置错误 –

+0

@SukhvirThapar你面临什么错误? – SilentKiller

+0

红色中的位置,无法解析符号'位置' –

0

首先定义一个可运行的

private Runnable runnable = new Runnable() { 

    @Override 
    public void run() { 
     changeImage(pos); 
    } 
}; 

不是创建一个处理程序

private Handler handler; 
handler = new Handler(Looper.getMainLooper()); 

在你changeImage方法

private void changeImage(int pos) { 
    yourImageView.setImageResource(imageArray[pos]); 
    handler.postDelayed(runnable, duration); 
} 

启动和停止运行的有:

handler.postDelayed(runnable, duration); 
handler.removeCallbacks(runnable); 

我希望这能帮到你。祝你好运。