如何每n秒更改一次imageview中的图像 [英] How to change images in imageview every n number of seconds
本文介绍了如何每n秒更改一次imageview中的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经创建了一个包含int中所有图像的数组,我想在imageView中每隔3秒更改一次这些图像,我已经尝试了所有可以找到的解决方案,但是显示出一些错误,我无法理解出去
I have made an array that has all the images in int and i want to change those images every 3 seconds in the imageView, I have tries all the solutions I could find but was showing some error, I can't figure it out .
java文件(home.java)
java file (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 file(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>
推荐答案
实现您的要求的最佳选择是您应该使用< a href =http://developer.android.com/reference/java/util/Timer.html =nofollow> 计时器
要更改每次3秒的图像如下。
Best option to achieve your requirement is You should use Timer
to change Image each of 3 seconds as follows.
// 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
这篇关于如何每n秒更改一次imageview中的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文