view pager timer should reset after swipe - android

I have a view pager that swipes every 6 seconds.I want the timer to reset to 6 after every manual swipe.
i.e if i swipe the page again the timer should start from 0.
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == NUM_PAGES) {
currentPage = 0;
}
pager.setCurrentItem(currentPage++, true);
}
};
Timer swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(Update);
}
}, 1, 6000);

private Handler handler;
private Runnable runnable;
private ViewPager pager;
private int currentPage = 0;
private int time = 3000; // 3 seconds
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
....
pager = (ViewPager) view.findViewById(R.id.pager);
pager.setOnPageChangeListener(this);
startSwipe();
....
}
private void startSwipe() {
MyLog.d(TAG, "startSwipe");
handler = new Handler();
runnable = new Runnable() {
#Override
public void run() {
if (currentPage == pager.getAdapter().getCount() - 1) {
currentPage = 0;
}
pager.setCurrentItem(currentPage++, true);
handler.postDelayed(runnable, time);
}
};
handler.postDelayed(runnable, time);
}
private void stopSwipe() {
MyLog.d(TAG, "stopSwipe");
handler.removeCallbacks(runnable);
}
#Override
public void onPageScrollStateChanged(int state) {
MyLog.d(TAG, "onPageScrollStateChanged state: " + state);
if (state == ViewPager.SCROLL_STATE_DRAGGING) {
stopSwipe();
startSwipe();
}
}
#Override
public void onPause() {
super.onPause();
MyLog.d(TAG, "onPause");
stopSwipe();
}
#Override
public void onResume() {
super.onResume();
MyLog.d(TAG, "onResume");
startSwipe();
}

Related

infinite loop - delay - separate threads

I am developing an application on Android.
I have an issue with a Fragment, the code can be found below.
The idea is to have an Image View display a list of Picture in an infinite loop. In order to realize this, I have created a new Thread, so as not to block the UI Thread. With a while (0 < 5) statement I create an infinite loop. Then I run an if...else statement to check on which Picture we are to determine the next picture to go to.
A Handler is used to take care of the 10 seconds delay between switching pictures. And finally another runnable takes care of the posting to the UI Thread.
This seems like a very complicated way of getting things done, anyone used the simpler code?
On top of that, somewhere in my code, there is an error. I cannot spot it, anyone?
Here is my code.
public class SecAct_Foto_Fragment extends Fragment {
int counter = 0;
View rootView;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.sec_act_photo_layout, container, false);
return rootView;
}
Thread myThread = new Thread(new Runnable() {
#Override
public void run() {
while (0 < 5) {
//so far it loops only once
//you start with run_rocks and but_left
final ImageView pic_view = (ImageView) rootView.findViewById(R.id.foto_groot);
final ImageView three_but = (ImageView) rootView.findViewById(R.id.knoppen);
//create a runnable for the picture view
pic_view.post(new Runnable() {
#Override
public void run() {
//every 10 seconds, switch picture and button fragment
if (counter == 0) {
final Handler handler0 = new Handler();
handler0.postDelayed(new Runnable() {
#Override
public void run() {
pic_view.post(new Runnable() {
#Override
public void run() {
pic_view.setImageResource(R.drawable.run_mount);
}
});
counter = 1;
}
}, 10000L);
} else if (counter == 1) {
final Handler handler1 = new Handler();
handler1.postDelayed(new Runnable() {
#Override
public void run() {
pic_view.post(new Runnable() {
#Override
public void run() {
pic_view.setImageResource(R.drawable.run_away);
}
});
counter = 2;
}
}, 10000L);
} else {
final Handler handler2 = new Handler();
handler2.postDelayed(new Runnable() {
#Override
public void run() {
pic_view.post(new Runnable() {
#Override
public void run() {
pic_view.setImageResource(R.drawable.run_rocks);
}
});
counter = 0;
}
}, 10000L);
}
}
});
myThread.start();
}
}
});
}
private class AsyncQueryRun extends AsyncTask {
#Override
protected Object doInBackground(Object[] objects) {
for (...){
////do what you want
runOnUiThread(new Runnable() {
#Override
public void run() {
///do what you want to be handled by UI thread
}});
SystemClock.sleep(60); ////wait as long as you want in mili sec.
}
}
#Override
protected void onPostExecute(Object o) {
}
}
You can use Handler in following way :
final ImageView pic_view = (ImageView) rootView.findViewById(R.id.foto_groot);
private int animationCounter = 1;
private Handler imageSwitcherHandler;
imageSwitcherHandler = new Handler(Looper.getMainLooper());
imageSwitcherHandler.post(new Runnable() {
#Override
public void run() {
switch (animationCounter++) {
case 1:
pic_view.setImageResource(R.drawable.run_mount);
break;
case 2:
pic_view.setImageResource(R.drawable.run_mount2);
break;
case 3:
pic_view.setImageResource(R.drawable.run_mount3);
break;
}
animationCounter %= 4;
if(animationCounter == 0 ) animationCounter = 1;
imageSwitcherHandler.postDelayed(this, 3000);
}
});
I have decided to try the solution of #NehaK and work with the ImageSwitcher View.
Added the following code in XML..
<ImageSwitcher
android:id="#+id/foto_groot_imageswitch"
android:layout_width="match_parent"
android:layout_height="220dp"
app:srcCompat="#drawable/run_rocks"
/>
Then used it in my Fragment..
public class SecAct_Foto_Fragment extends Fragment {
int counter = 0;
View rootView;
private ImageSwitcher pic_image_switch;
private Handler pic_image_switch_handler;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.sec_act_photo_layout, container, false);
/*Animation anim_in = AnimationUtils.loadAnimation(getActivity(), R.anim.enter_from_left);
pic_image_switch.setInAnimation(anim_in);*/
//pic_image_switch = new ImageSwitcher(getActivity());
pic_image_switch = (ImageSwitcher) rootView.findViewById(R.id.foto_groot_imageswitch);
pic_image_switch.setFactory(new ViewSwitcher.ViewFactory() {
#Override
public View makeView() {
ImageView imageView = new ImageView(getActivity());
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setLayoutParams(new ImageSwitcher.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
return imageView;
}
});
pic_image_switch_handler = new Handler(Looper.getMainLooper());
pic_image_switch_handler.post(new Runnable() {
#Override
public void run() {
switch (counter) {
case 0:
pic_image_switch.setImageResource(R.drawable.run_mount);
break;
case 1:
pic_image_switch.setImageResource(R.drawable.run_away);
break;
case 2:
pic_image_switch.setImageResource(R.drawable.run_rocks);
break;
}
counter += 1;
if (counter == 3) {
counter = 0;
}
pic_image_switch.postDelayed(this, 1000);
}
});
return rootView;
}
}

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

Android update ProgressBar with Handler

I would like to update the progressBar with Handler and for loop but without success.
Code:
public void increase_splash_bar (int from, int to)
{
Handler handler1 = new Handler(Looper.getMainLooper());
for (progress_k = from; progress_k<=to ;progress_k++)
{
handler1.postDelayed(new Runnable()
{
#Override
public void run()
{
FrontLayout.update_splash_progress_bar(progress_k, 100);
}
}, 2000);
}
}
Question:
The progress bar increase immediately to the end value instead of progressively.
Why?
Try this:
public void increase_splash_bar (int from, int to)
{
Handler handler1 = new Handler(Looper.getMainLooper());
for (progress_k = from; progress_k<=to ;progress_k++)
{
final int curr_progress_k = progress_k;
handler1.postDelayed(new Runnable()
{
#Override
public void run()
{
FrontLayout.update_splash_progress_bar(curr_progress_k, 100);
}
}, progress_k * 100); // adjust "100" value to adjust speed
}
}
Repeat a task with a time delay?
#inazaruk
private ProgressBar progressBar;
private Handler mHandler;
private int progressInt = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
progressBar = (ProgressBar) findViewById(R.id.pb);
progressBar.setProgress(0);
mHandler = new Handler();
runnable.run();
}
Runnable runnable = new Runnable() {
#Override
public void run() {
try {
updateProgress();
} catch (Exception ignored) {
} finally {
mHandler.postDelayed(runnable, progressInt);
}
}
};
private void updateProgress() {
progressInt += 1;
if (progressInt > 100) {
mHandler.removeCallbacks(runnable);
} else {
progressBar.setProgress(progressInt);
}
}
try this code:
Solution 1
public void increase_splash_bar (int from, int to)
{
Handler handler1 = new Handler();
class Task implements Runnable {
int start,end;
Task(int a,int b) { start = a; end = b;}
#Override
public void run() {
for (int i =start ; i <= end; i++) {
final int value = i;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler1.post(new Runnable() {
#Override
public void run() {
progressBar.setProgress(value);
}
});
}
}
}
Thread t = new Thread(new Task(from, to)); //call it
t.start();
}
Solution 2: More Simple
If thread is too much to ask for this problem..
you can use the following solution to use a single Handler to update progressbar:
code
public class HandlerDemo extends Activity
{
ProgressBar bar;
Handler handler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
bar.incrementProgressBy(5);
}
};
boolean isRunning = false;
#Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
bar = (ProgressBar) findViewById(R.id.progress);
}
public void onStart()
{
super.onStart();
bar.setProgress(0);
Thread background = new Thread(new Runnable()
{
public void run()
{
try
{
for (int i = 0; i < 20 && isRunning; i++)
{
Thread.sleep(1000);
handler.sendMessage(handler.obtainMessage());
}
}
catch (Throwable t)
{
// just end the background thread
}
}
});
isRunning = true;
background.start();
}
public void onStop()
{
super.onStop();
isRunning = false;
}
}
Hope it helps..

Increasing counter in TimerTask

How can I increase my counter i here:
private void startTimer() {
int i = 0;
final Timer timer = new Timer();
final TimerTask task = new TimerTask() {
#Override
public void run() {
if(preferences.getBoolean(IS_RUNNING_KEY, false))
{
final int k = i++; //i must declared final error
runOnUiThread(new Runnable() {
#Override
public void run() {
timeCounter.setText(""+k);
Log.d("DTAG","K: "+k);
}
});
} else {
timer.cancel();
timer.purge();
}
}
};
timer.schedule(task, 1000);
}
You have to move i out of the scope of the function. Then it does not have to be declared final and you can change it. Change your code to this
private int i = 0;
private void startTimer() {
final Timer timer = new Timer();
final TimerTask task = new TimerTask() {
#Override
public void run() {
if(preferences.getBoolean(IS_RUNNING_KEY, false))
{
final int k = i++;
runOnUiThread(new Runnable() {
#Override
public void run() {
timeCounter.setText(""+k);
Log.d("DTAG","K: "+k);
}
});
} else {
timer.cancel();
timer.purge();
}
}
};
timer.schedule(task, 1000);
}

Automatic Scrolling View pager page with few interval

I have used android view pager to display images and text now what i want is that smothly scrolling pages after few seconds and with animation?
Its works but not smothly viewpager pages scroll.
Timer call
mCountDownTimer = new MyCountDownTimer(4000, 1000);
mCountDownTimer.start();
.
private static MyCountDownTimer mCountDownTimer;
private class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
System.out.println("Time's up!");
startTimerWithAnim();
}
#Override
public void onTick(long millisUntilFinished) {
System.out.println("mill="+millisUntilFinished / 1000);
}
}
if the 'MyCountDownTimer' call then the 'startTimerWithAnim' method call
public static void startTimerWithAnim() {
if (mCountDownTimer != null)
mCountDownTimer.cancel();
mHandler = new Handler();
mRunnable = new Runnable() {
public void run() {
if (mMemberPagerAdapterList != null) {
if (mPagedGrid.getCurrentItem() == mMemberPagerAdapterList.getCount() - 1)
mPagedGrid.setCurrentItem(0, true);
else if (isFirstTimeCurrentItem) {
mPagedGrid.setCurrentItem(0, true);
isFirstTimeCurrentItem = false;
} else if (isFirstTimeCurrentItem == false)
mPagedGrid.setCurrentItem(mPagedGrid.getCurrentItem() + 1, true);
}
}
};
mTimer = new Timer();
mTimer.schedule(new TimerTask() {
#Override
public void run() {
mHandler.post(mRunnable);
}
}, 100, 4000);
}
There you go!
class UpdateTimeTask extends TimerTask {
public void run() {
viewPager1.post(new Runnable() {
public void run() {
if(viewPager1.getCurrentItem()<i){
viewPager1.setCurrentItem(viewPager1.getCurrentItem()+1,true);
String abc = String.valueOf(viewPager1.getCurrentItem());
Log.i("timer_+",abc);
}
else
{
viewPager1.setCurrentItem(0,true);
}
}
});
}
}
Timer timer = new Timer();
timer.schedule(new UpdateTimeTask(), 2000, 4000);
function doSomething() {
$(document).scrollTop($(document).height());
}
setInterval(doSomething, 5000);
This will scroll to bottom of the page every 5 seconds. This will be useful, if you have auto load content when user scroll down (like Facebook).

Categories

Resources