Control View Pager Slides with Timer Task - android

I'm trying to slide my ViewPager automatically via using TimerTask class, seems I do not have proper delay and period, it is sliding so fast. I tried all possible combinations of delay and period parameters without any luck, still so annoying fast sliding. Below is the code:
class SliderTimer extends TimerTask {
#Override
public void run() {
HomeActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
if (viewPager.getCurrentItem() < listSlides.size() - 1) {
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
} else {
viewPager.setCurrentItem(0);
}
}
});
}
}
And the implementations:
Timer timer = new Timer();
timer.scheduleAtFixedRate(new HomeActivity.SliderTimer(), 10000, 10000);
Please guide me, what best can be done for the same.

I think Using Handler is better then TimerTask in this case if ViewPager can slide manually too.
First Create a Handler and Runnable Globally.
private Handler handler=new Handler();
private Runnable runnable=new Runnable() {
#Override
public void run() {
if(pagerSlider.getCurrentItem()==data.size()-1){
pagerSlider.setCurrentItem(0,false);
}else{
pagerSlider.setCurrentItem(pagerSlider.getCurrentItem()+1);
}
}
};
Post the runnable inside onPageChange.
pagerSlider.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener(){
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
handler.removeCallbacks(runnable);
handler.postDelayed(runnable,2000);
}
});
You need to post for first time Rest the listener will do. Change the delay as per your need :-
handler.postDelayed(runnable,2000);
I just realize that you might be asking about scrolling velocity . Well for this you need to use Customize Scroller. Go to This thread.

Try this one...
public static final long DELAY_MS = 2000;
public static final long PERIOD_MS = 4000;
new MyTimerHeader(DELAY_MS, PERIOD_MS, viewPager, images_total_length);
public MyTimerHeader(long DELAY_MS, long PERIOD_MS, final ViewPager slider1, final
int image_name) {
final int image_name1=image_name;
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
int currentPage = slider1.getCurrentItem();
if (currentPage == image_name1 - 1) {
currentPage = 0;
}
else {
currentPage = currentPage + 1;
}
slider1.setCurrentItem(currentPage);
}
};
Timer timer = new Timer(); // This will create a new Thread
timer .schedule(new TimerTask() { // task to be scheduled
#Override
public void run() {
handler.post(Update);
}
}, DELAY_MS, PERIOD_MS);
}

Related

Can I slide an android viewpager within a different time slot?

I want to slide my an android viewpager within a different slide slot.It means first page comes after the 5 second and second page will be appearing in 8 second.I need to slide viewpager but that slides are need to come within different time frame.is it possible to do that thing? Any help to slow this error would be highly appreciated.
I did the following code segment.But it will change viwepager for some constant time period.
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == signageResourceStoreModelList.size()) {
currentPage = 0;
}
try {
viewPager.setCurrentItem(currentPage, true);
} catch (Exception e) {
e.printStackTrace();
}
currentPage = currentPage + 1;
}
};
timer = new Timer();
timer.schedule(new TimerTask() { // task to be scheduled
#Override
public void run() {
handler.post(Update);
}
}, DELAY_MS, PERIOD_MS);
}
Yes, definitely you can do this by some programming logic.
Declare a class variable
for eg. int time=2000;
To change the view inside viewpager programmatically
public void MoveNext(View view) {
pager.setCurrentItem(pager.getCurrentItem() + 1);
//Write logic of incrementing time here
//e.g.time=time+1000;
}
Now define a handler
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
MoveNext();
}
},time);

How to change page in ViewPager Android?

I am using View Pager in my App. I need to trigger page change every 1 min. I know that if user swipes, page change happens. But if we have to trigger it, is there any API for it.
How to change page in ViewPager Android?
Use ViewPager.setCurrentItem(int item) for changing ViewPager pages programmatically.
Where item is index of Page which want to set as current item in ViewPager.
private int mInterval = 5000; // 5 seconds by default, can be changed later
private Handler mHandler;
#Override
protected void onCreate(Bundle bundle) {
...
mHandler = new Handler();
startRepeatingTask();
}
Runnable mStatusChecker = new Runnable() {
#Override
public void run() {
updatePage(); //this function can change value of mInterval.
mHandler.postDelayed(mStatusChecker, mInterval);
}
};
void startRepeatingTask() {
mStatusChecker.run();
}
void stopRepeatingTask() {
mHandler.removeCallbacks(mStatusChecker);
}
private void updatePage(){
viewPager.setCurrentItem(pageno)
}
Handler handler = new Handler();
handler.post(new Updater());
class Updater implements Runnable {
public void run() {
mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1);
if (mViewPager.getAdapter().getCount() - 1 > mViewPager.getCurrentItem()){
handler.postDelayed(new Updater, 60000);
}
}
}
You can use CountDownTimer do this easily.Change the page after every 60sec using below example
class MyTimer extends CountDownTimer{
public MyTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long l) {
}
#Override
public void onFinish() {
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
myTimer.start();
}
MyTimer myTimer = new MyTimer(1000*60, 1000);
myTimer.start();

Repeat a Method for specific times in android

Here is a code which I want to repeat 50 times after every 3 seconds. if I am calling this function with 'for' loop or 'while' loop it is not working properly Please give me suggestion.
for (int i = 0; i < 50; i++) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
Generate_Ballon();
}
}, delay);
}
You can use CountDownTimer
See Example,
new CountDownTimer(150000, 3000)
{
public void onTick(long millisUntilFinished)
{
// You can do your for loop work here
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
Here onTick() method will get executed on every 3 seconds.
You should use Handler's postDelayed function for this purpose. It will run your code with specified delay on the main UI thread, so you will be able to update UI controls.
private int mInterval = 5000; // 5 seconds by default, can be changed later
private Handler mHandler;
#Override
protected void onCreate(Bundle bundle) {
...
mHandler = new Handler();
}
Runnable mStatusChecker = new Runnable() {
#Override
public void run() {
updateStatus(); //this function can change value of mInterval.
mHandler.postDelayed(mStatusChecker, mInterval);
}
};
void startRepeatingTask() {
mStatusChecker.run();
}
void stopRepeatingTask() {
mHandler.removeCallbacks(mStatusChecker);
}
private int count = 50;
private Handler handler = new Handler();
private Runnable r = new Runnable() {
public void run() {
Generate_Ballon();
if (--count > 0) {
handler.postDelayed(r, delay);
}
}
};
handler.postDelayed(r, delay);

Android ViewPager automatically change page

I want to schedule an action to change automatically my ViewPager pages.
I've tried:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
if (currentPage == NUM_PAGES) {
currentPage = 0;
}
featureViewPager.setCurrentItem(currentPage++, true);
}
}, 100, 500);
but I'm always getting:
E/AndroidRuntime(5381): FATAL EXCEPTION: Timer-0
E/AndroidRuntime(5381): java.lang.IllegalStateException: Must be called from main thread of process
I'm already in main thread right? How can I solve this?
Thanks for your time.
EDIT:
====================================
Thanks for all your answers. Based on these responses I came across 2 solutions:
Solution 1:
swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (currentPage == NUM_PAGES) {
currentPage = 0;
}
featureViewPager.setCurrentItem(currentPage++, true);
}
});
}
}, 500, 3000);
Solution 2:
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == NUM_PAGES) {
currentPage = 0;
}
featureViewPager.setCurrentItem(currentPage++, true);
}
};
swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(Update);
}
}, 500, 3000);
Which one is better or they are the same?
Thanks once again.
If you want to use thread in the main UI then you need to use a hander to hand it.
Handler handler = new Handler();
Runnable update = new Runnable() {
public void run() {
if ( currentPage == NUM_PAGES ) {
currentPage = 0;
}
featureViewPager.setCurrentItem(currentPage++, true);
}
};
new Timer().schedule(new TimerTask() {
#Override
public void run() {
handler.post(update);
}
}, 100, 500);
Easiest way how to solve it is to create an postDelayed runnable
private Handler mHandler;
public static final int DELAY = 5000;
Runnable mRunnable = new Runnable()
{
#Override
public void run()
{
//TODO: do something like mViewPager.setCurrentPage(mIterator);
mHandler.postDelayed( mRunnable , DELAY );
}
};
as You can see it will loop infinitelly. When you want to stop it, just simply call
mHandler.removeCallbacks( mRunnable );
The TimerTask will runs on it's own thread ( = not the UI thread).
You can simply call setCurrentItem directly on the main thread using a Handler.
For the kotlin extension lover. This can be helpful on viewPage2 auto page change
fun ViewPager2.enableAutoScroll(totalPages: Int): Timer {
val autoTimerTask = Timer()
var currentPageIndex = currentItem
autoTimerTask.schedule(object : TimerTask() {
override fun run() {
currentItem = currentPageIndex++
if (currentPageIndex == totalPages) currentPageIndex = 0
}
}, 0, DELAY_FOUR_SECONDS)
// Stop auto paging when user touch the view
getRecyclerView().setOnTouchListener { _, event ->
if (event.action == MotionEvent.ACTION_DOWN) autoTimerTask.cancel()
false
}
return autoTimerTask // Return the reference for cancel
}
fun ViewPager2.getRecyclerView(): RecyclerView {
val recyclerViewField = ViewPager2::class.java.getDeclaredField("mRecyclerView")
recyclerViewField.isAccessible = true
return recyclerViewField.get(this) as RecyclerView
}

Android Imageswitcher: switch images periodically?

I am using an ImageSwitcher with a TouchListener to change images from an array. Its working fine but i want it to switch images every x seconds or so, so that I can add imageSwitcher.setImageResource(imageList[curIndex]); to it.
Any suggestions?
Try this,
imageSwitcher.postDelayed(new Runnable() {
int i = 0;
public void run() {
imageSwitcher.setImageResource(
i++ % 2 == 0 ?
R.drawable.image1 :
R.drawable.mage2);
imageSwitcher.postDelayed(this, 1000);
}
}, 1000);
I think it is possible via TimerTask and Timer. please Try this code. I think It help you.
private Handler mHandler;
private Runnable mUpdateResults;
private Timer timerAnimate;
private TimerTask timerTask;
mHandler = new Handler();
mUpdateResults = new Runnable() {
public void run() {
AnimateandSlideShow();
}
};
int delay = 0;
int period = 15000;
timerAnimate = new Timer();
timerTask = new TimerTask() {
public void run() {
mHandler.post(mUpdateResults);
}
};
timerAnimate.scheduleAtFixedRate(timerTask, delay, period);
Public void AnimateandSlideShow()
{
imageSwitcher.setImageResource(imageList[curIndex]);
///Here You need To handle curIndex position.
}

Categories

Resources