gpt4 book ai didi

java - 如何每隔 n 秒更改 imageview 中的图像

转载 作者:行者123 更新时间:2023-12-01 22:21:22 25 4
gpt4 key购买 nike

我已经制作了一个数组,其中包含 int 中的所有图像,我想在 imageView 中每 3 秒更改一次这些图像,我已经尝试了我能找到的所有解决方案,但显示了一些错误,我无法理解出去 。

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>

最佳答案

实现您的要求的最佳选择是您应该使用 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

关于java - 如何每隔 n 秒更改 imageview 中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29713990/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com