Reputation: 90
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 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 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>
Upvotes: 0
Views: 3722
Reputation: 6942
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
Upvotes: 6
Reputation: 11921
first define a runnable
private Runnable runnable = new Runnable() {
@Override
public void run() {
changeImage(pos);
}
};
Than create a handler
private Handler handler;
handler = new Handler(Looper.getMainLooper());
In your changeImage method
private void changeImage(int pos) {
yourImageView.setImageResource(imageArray[pos]);
handler.postDelayed(runnable, duration);
}
Start and stop runnable with:
handler.postDelayed(runnable, duration);
handler.removeCallbacks(runnable);
I hope this'll help you. Good luck.
Upvotes: 0
Reputation: 3785
use a CountDownTimer
here is how: How to make a countdown Timer in android?
and change the image view background inside onFinish()
.
hope this will work out for you
Upvotes: 0