Update postdelay seconds for runnable when page scrolled in viewpager android? - android

i am displaying images using viewpager and that images will be automatically change after 20 seconds automatically changes images every 20 seconds work perfectly but i want to reset handler postdelayed time if user manually scroll pager and next image should be display 20 seconds
Current Working :
if i am on the first position of viewpager for display image this image time is 20 seconds
after 10 seconds if i scrollpage than next image is display is only 10 seconds but it should be display 20000 seconds
how to update post delayed time for next image display
check below code what i have tried.
onpageselected i have set again post delayed but it was not worked
Thanks
final int []sliderImageArray={R.drawable.a,R.drawable.b,R.drawable.c,R.drawable.d,R.drawable.e};
runnable = new Runnable()
{
//int i=0;
public void run()
{ // slider image run
if(startt)
{
if(i==0)
{
viewPager.setCurrentItem(i,false);
}
else
{
viewPager.setCurrentItem(i,false);
}
i++;
if(i>sliderImageArray.length-1)
{
i=0;
}
}
else
{
}
imagehandler.postDelayed(this, 20000);
}
};
imagehandler.postDelayed(runnable,20000);
.
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
i=arg0;
imagehandler.postDelayed(runnable, 20000);
Log.d("onpageselected","----->"+arg0);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});

You should call the imagehandler in onPageScrollStateChanged.
So call imagehandler.postDelayed if the ViewPager is in the process of settling to the next position and call imagehandler.removeCallbacks if the ViewPager is being dragged by the user ViewPager Scroll-States.
Here is an example implementation:
final int[] sliderImageArray = new int[] { R.drawable.a, R.drawable.b,
R.drawable.c, R.drawable.d, R.drawable.e };
private Runnable imageSliderRunnable = new Runnable() {
#Override
public void run() {
final int itemCount = sliderImageArray.length;
final int currentItem = viewPager.getCurrentItem();
final int nextItem = (currentItem + 1) % itemCount;
viewPager.setCurrentItem(nextItem, false);
}
};
private void setupViewPager() {
this.viewPager
.setOnPageChangeListener(new SimpleOnPageChangeListener() {
#Override
public void onPageScrollStateChanged(int state) {
switch (state) {
case ViewPager.SCROLL_STATE_DRAGGING:
imagehandler.removeCallbacks(imageSliderRunnable);
break;
case ViewPager.SCROLL_STATE_SETTLING:
imagehandler.removeCallbacks(imageSliderRunnable);
imagehandler.postDelayed(imageSliderRunnable, 20000);
break;
}
}
});
imagehandler.postDelayed(imageSliderRunnable, 20000);
}
DonĀ“t forget to remove the callbacks from the handler if enclosing Activity or Fragment will be paused.
#Override
public void onResume() {
super.onResume();
setupViewPager();
}
#Override
public void onPause() {
imagehandler.removeCallbacks(imageSliderRunnable);
super.onPause();
}

Try do this
imagehandler.removeCallbacksAndMessages(null);
imagehandler.postDelayed(this, 20000);

Here you can do like this way
private int runnableMill = 20000;
now use this object
imagehandler.postDelayed(runnable, runnableMill);
update time
runnableMill = 10000;
On the next execution it will be use new value to execute your thread

Related

Why my Image Slider is Swipe Fast after Comeback to Activity or Fragment android

I try to get Image from Server side and make Image Slider to swipe and Automatic Swipe Slider using Timer() ,in that Fragment my slider work perfectly but when i going to other Activity or Fragment and comeback to Slider Fragment slider goes slide fast, but i don't understand what wrong with my code . Please check my code :- (I use Fragment)
private void slider() {
mPager.setAdapter(new SlidingImage_Pager_Adapter(getContext(), imageModelArrayList));
indicator.setViewPager(mPager);
final float density = getResources().getDisplayMetrics().density;
//Set circle indicator radius
indicator.setRadius(5 * density);
NUM_PAGES = imageModelArrayList.size();
// Auto start of viewpager
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == NUM_PAGES) {
currentPage = 0;
}
mPager.setCurrentItem(currentPage++, true);
}
};
// Automatic Swip viewPager
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(Update);
}
}, 3500, 3500);
// Pager listener over indicator
indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
currentPage = position;
}
#Override
public void onPageScrolled(int pos, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int pos) {
}
});
}
#Override
public void onDestroyView() {
super.onDestroyView();
swipeTimer.cancel();
}
I also put swipeTimer cancel in onDestroyView() method but it's not working for me.

Control View Pager Slides with Timer Task

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);
}

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 the image automatically in view pager when it reaches the last image it should come to the first image automatically

I am now implementing the view pager and i want to continuously change the image one by one automatically for a particular periods of time may be once in 5 ms .
I also have to manually allow the user to swipe the images (it is working properly)
But the image is not automatically changing and when it reaches the last image it should come to the first image automatically
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == strImages.length-1) {
currentPage = 0;
}
intro_images.setCurrentItem(currentPage++, true);
}
};
timer = new Timer(); // This will create a new Thread
timer .schedule(new TimerTask() { // task to be scheduled
#Override
public void run() {
handler.post(Update);
}
}, 500, 3000);
I used above code but it does not work properly
try this add addOnPageChangeListener to your viewPager like this
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (position == strImages.length-1) {
currentPage = 0;
}
intro_images.setCurrentItem(currentPage++, true);
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
or for auto change page try this create a time task like this
Timer timer;
timer = new Timer();
timer.scheduleAtFixedRate(new RemindTask(), 0, 3000); // delay*/
private class RemindTask extends TimerTask {
int current = viewPager.getCurrentItem();
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
if (current < strImages.size()) {
viewPager.setCurrentItem(current);
current += 1;
} else {
current = 0;
viewPager.setCurrentItem(current);
}
}
});
}
}
The below code is to get the last position and to scroll to the 1st position:
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener()
{
#Override
public void onPageScrolled(int position, float positionOffset,int positionOffsetPixels) {
if (position == Yourlist.size()-1) {
pager.setCurrentItem(0);
}
pager.setCurrentItem(position++,true);
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
The below code is For automatic change picture in every 10s using CountDown Timer:
- First you have to declare one array,which will contain your
images,then after you have to use below code.
int i=0;
new CountDownTimer(1000,1000)
{
#Override
public void onTick(long millisUntilFinished) {}
#Override
public void onFinish() {
iV.setImageDrawable(sdk.getContext().getResources().getDrawable(array[i]));
i++;
if(i== array.length-1) {i=0;}
start();
}
}.start();
You don't need the combination of Handler and TimerTask for this, You can use simple Handler like this using Handler.postDelayed
private Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
int totalCount = intro_images.getAdapter().getCount();
int currentItem = intro_images.getCurrentItem();
if (currentItem == (totalCount - 1)) {
currentItem = 0;
} else {
currentItem = currentItem + 1;
}
intro_images.setCurrentItem(currentItem, true);
handler.postDelayed(this, 3000);
}
};
#Override
protected void onResume() {
super.onResume();
handler.postDelayed(Update, 500);
}
#Override
protected void onPause() {
super.onPause();
if(handler != null) {
handler.removeCallbacks(Update);
}
}
just add listener to your viewpager to get the last position and to scroll to the 1st position.
vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
if(position==yourlist.length){
vp.setCurrentItem(0);
}
}
});
AnimationDrawable animation = new AnimationDrawable();

Stop Handler when Fragment is destroyed

I am starting handler in a fragment like below :
public class FeedsFragment extends Fragment{
private Handler handler;
private Runnable runnableCode;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Create the Handler object (on the main thread by default)
handler = new Handler();
// Define the task to be run here
runnableCode = new Runnable() {
#Override
public void run() {
// Get the No of New Feeds
getFeedCounts();
// Repeat this runnable code again every 30 seconds
handler.postDelayed(runnableCode, 30,000);
}
};
handler.post(runnableCode);
}
#Override
public void onDetach() {
super.onDetach();
handler.removeCallbacksAndMessages(runnableCode);
}
#Override
public void onDestroyView() {
handler.removeCallbacksAndMessages(runnableCode);
super.onDestroyView();
}
#Override
public void onPause() {
super.onPause();
handler.removeCallbacksAndMessages(runnableCode);
}
#Override
public void onResume() {
/**
* Start the handler again if coming back from any profile page
* or hashtag search
*/
isHandlerStopped = false;
handler.post(runnableCode);
super.onResume();
}
I am removing all callbacks in onDetach and onDestroyView functions, but it is not working.
When I load a different fragment in the same activity this handler
doesn't stop itself, handler stops only when I load some other
activity in my application.
I want this handler to run only when the fragment in which I am using it is loaded in the activity, if some other fragment is being loaded in the same activity it should be stopped.
Also, this fragment is inside viewpager, so when I switch the tab and other fragment gets loaded the handler doesn't stop. Please check the below code in activity :
ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
FeedsFragment feedsFragment;
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
// when user do a swipe the selected tab change
switch (position){
case 0:
break;
case 1:
feedsFragment.removeHandler();
break;
case 2:
feedsFragment.removeHandler();
break;
case 3:
feedsFragment.removeHandler();
break;
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
FragmentAdapter adapter = new FragmentAdapter(getActivity().getSupportFragmentManager());
feedsFragment = FeedsFragment.newInstance(bundle);
adapter.addFragmentWithIcon(FeedsFragment.newInstance(null))
, mContext.getResources().getString(R.string.feed_tab_name));
adapter.addFragmentWithIcon(FeedFriendRequests.newInstance(null),
mContext.getResources().getString(R.string.requests_tab_name));
adapter.addFragmentWithIcon(NewMessagesFragment.newInstance(null), mContext.getResources().getString(R.string.message_tab_name));
adapter.addFragmentWithIcon(NotificationFragment.newInstance(null)
, mContext.getResources().getString(R.string.notification_tab_name));
pager.setAdapter(adapter);
When I select any other tab at that time I'm calling the method removeHandler in FeedFragment.
public void removeHandler(){
handler.removeCallbacks(runnableCode);
}
But still handler is getting called.
Please help me if anyone have idea about this.
Thanks a lot in advance
I don't think it has to do with your fragment lifecycle. You need to replace
handler.removeCallbacksAndMessages(runnableCode);
// this does not seem to work
with
handler.removeCallbacks(runnableCode);
Just an alternative create a method in FeedsFragment
public void removeHandler()
{
Log.i("Stop Handler ","Yes");
handler.removeCallbacks(runnableCode);
}
In activity when you want to replace fragment
if(feedsFragment.isAdded())
{
feedsFragment.removeHandler();
}
...// rest of the code to replace the fragment with new one
Edit:
viewPager.addOnPageChangeListener(pageChangeListener);
viewPager.post(new Runnable() {
#Override
public void run() {
pageChangeListener.onPageSelected(0);
}
});
Then
ViewPager.OnPageChangeListener pageChangeListener = new ViewPager.OnPageChangeListener() {
int currentPosition = 0;
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int newPosition) {
FragmentLifeCycle fragmentToShow = (FragmentLifeCycle) adapter.getItem(newPosition);
fragmentToShow.onResumeFragment();
if(newPosition==0)
{
currentPosition = newPosition;
}else {
FragmentLifeCycle fragmentToHide = (FragmentLifeCycle) adapter.getItem(currentPosition);
fragmentToHide.onPauseFragment();
currentPosition = newPosition;
}
}
Have a interface
public interface FragmentLifeCycle {
void onPauseFragment();
void onResumeFragment();
}
Implement the interface in all fragments. Assuming the handler is used in Fragment at position 0.
#Override
public void onPauseFragment() {
if(handler!=null)
handler.removeCallbacks(runnableCode);
}
#Override
public void onResumeFragment() {
handler = new Handler();
// Define the task to be run here
runnableCode = new Runnable() {
#Override
public void run() {
Log.i("Do ","Something");
handler.postDelayed(runnableCode, 3000);
}
};
handler.post(runnableCode);
}
In other fragment just implement the interface and do nothing.

Categories

Resources