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);
Related
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);
}
I need to update a TextView frequently with a specific time delay in the android studio. The code is below. Thank you.
Edit: I also need to end the loop with a button click or with an "if" control.
//INFLATION CALCULATION !!!
/**
* This method calculates Inflation value.
*/
public void calculateInflation() {
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
inflation = (cpi-cpiIni)/cpiIni*100;
displayInflation();
cpiIni = cpi;
}
}, delay*12);
}
Call the same method inside the runnable in order to keep the loop going
Use a flag in order to be able to stop the loop: shouldCalculate
private boolean shouldCalculate = true; // set to false when you want to end the loop
public void calculateInflation() {
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
if (shouldCalculate) {
inflation = (cpi-cpiIni)/cpiIni*100;
displayInflation();
cpiIni = cpi;
calculateInflation();
}
}
}, delay*12);
}
private Runnable updateTimerThread = new Runnable() {
public void run() {
inflation = (cpi-cpiIni)/cpiIni*100;
displayInflation();
cpiIni = cpi;
customHandler.postDelayed(this, 0);
}
};
public void startTimer() {
//timer
startTime = SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread, 0);
}
public void stopTimer() {
//timer stops
customHandler.removeCallbacks(updateTimerThread);
//timer ends
}
make a reference of runnable thread , start it using startTimer() and remove thread using stopTimer() as you said on a button click or up on a specific conditions .Also you can change the postDelayed milliseconds as ur wish
Try below code. This will do the trick. If you find any problem please let me know.
public void calculateInflation() {
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
inflation = (cpi-cpiIni)/cpiIni*100;
displayInflation();
cpiIni = cpi;
if(shouldRepeat)
calculateInflation();
}
}, delay*12);
}
And second approach can be CountDownTimer. Make a method as shown in below code
public void timerTask(final int loopTime){
//Loop time is the actual time for repeatation
new CountDownTimer(loopTime, 1000) {
public void onTick(long millisUntilFinished) {
//this tells you one second is passed
}
public void onFinish() {
//here on time finish you need to define your task
inflation = (cpi-cpiIni)/cpiIni*100;
displayInflation();
cpiIni = cpi;
//call the same method again for looping
timerTask(loopTime);
}
}.start();
}
Simplest way. Here updateRunnable calls itself with delay. Make updateRunnable as global variable to access from anywhere.
Runnable updateRunnable = new Runnable() {
#Override
public void run() {
inflation = (cpi-cpiIni)/cpiIni*100;
displayInflation();
cpiIni = cpi;
handler.postDelayed(this, UPDATE_TIME);
}
};
Start handler. Here we start handler immediately without delay.
handler.postDelayed(updateRunnable, 0)
Stop handler
handler.removeCallbacks(updateRunnable)
By the way don't forget to stop handler on onDestroy()
Using Android studio, I am trying to make an app that gets data from a web-service and display the data and updates the view every 5 sec or when the data on the web-service changes. With this I am trying to change the colours on some button based on an int, the int changes and the color on the button changes when I apply buttons(); to another button and then presses it but I want it to update by itself.
When I used a while loop the app gets stuck
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
buttons();
}
});
The runOnUiThread is placed in the onCreate.
using run on UI thread will cause your UI to freeze , try using a timer task instead .
example :
#Override
public void StopTimerTask() {
if (timer != null) {
timer.cancel();
timer = null;
}
}
public void StartTimer() {
timer = new Timer();
initializeTimerTask();
int UpdateTime = Integer.valueOf(UserSettings.getString("Update", "60000"));
timer.schedule(doAsynchronousTask, 0, YOURTIME);
}
public void initializeTimerTask() {
doAsynchronousTask = new TimerTask() {
#Override
public void run() {
myHandler.post(new Runnable() {
public void run() {
YOUR LOGIC HERE
}
});
}
};
}
doing this where u just put another class into main activity was succesful only problem is that it have to be in my main class
public class updategui extends TimerTask {
Activity context;
Timer timer;
public updategui(Activity context, int seconds) {
this.context = context;
timer = new Timer();
timer.schedule(this,
seconds * 1000, // initial delay
seconds * 1000); // subsequent rate
}
#Override
public void run() {
if(context == null || context.isFinishing()) {
this.cancel();
return;
}
context.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
buttons();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}}
I have a textview which i want to change with a thread and do it again and again (Like a digital clock). But i'm having problems with setting time between 2 changes. Here, the code:
display1 = (TextView) findViewById(R.id.textView1);
Thread timer2 = new Thread(){
#Override
public void run() {
synchronized (this){
runOnUiThread(new Runnable() {
#Override
public void run() {
int i = 0;
display1.setText("" + i);
try {
sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
display1.setText("" + (i+1));
}
});
}
}
};
timer2.start();
This sleep(2000); function makes textview invisible for the given time but i want it stand still till the next change. How can i do that?
But i'm having problems with setting time between 2 changes
Do NOT do sleep() on your UI thread. If you want to chain some actions with the delay, split your code into two runnables and the first one should set display1 and then post second runnable with the delay using postDelayed()
EDIT
want one of them to increase 3 per sec, and the other 5 per sec until they reach 1000 for instance
You can make your Runnable post itself until some criteria are met (i.e. time, counter value etc). Just at the end your Runnable check your conditions and if not met, call postDelayed(this, delay); and you are good.
You should use a Handler instead and dispatch your changes to the UI thread.
Handler mHandler = new Handler();
mHandler.post(new Runnable() {
#Override
public void run() {
// Code to be run right away
}
});
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
// Code to be run after 2 seconds
}
}, 2000);
Maybe split up what you need to do into separate methods. Here you have a UI method and a sleep method split up. Hope it helps
private void myMethod() {
new Thread() {
#Override
public void run() {
int i = 0;
doWorkOnUI(String.valueOf(i));
pause(2000);
doWorkOnUI(String.valueOf(i++));
}
}.start();
}
private void pause(int pauseTime) {
try {
Thread.sleep(pauseTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void doWorkOnUI(final String string) {
runOnUiThread(new Runnable() {
#Override
public void run() {
display1.setText(string);
}
});
}
I have an image view. So in the image view i want to change the images after a certain time period. Images are coming from an array list. Now when the no of images are 3 or more than 3, it is working perfect. But when it is 2, my logic is not working. Second image is visible for a moment and then again changed to first image here is my code:
r = new Runnable(){
int i = 0;
public void run(){
iv.setImageBitmap(alBmps.get(i));
i++;
if(i >= alBmps.size()){
i = 0;
}
iv.postDelayed(r, 5000); //set to go off again in 5 seconds.
}
};
iv.postDelayed(r, 1000);
Can any one help me what changes i need on the above code?
Thanks.
Try this
declare variables
static int i=0;
private Timer myTimer;
in your onCreate or on button click where you want to call and start the methods
myTimer = new Timer();
myTimer.schedule(new TimerTask()
{
#Override
public void run()
{
TimerMethod();
}
}, 500, 5000);
add these methods to your class
private void TimerMethod()
{
this.runOnUiThread(Timer_Tick);
}
private Runnable Timer_Tick = new Runnable()
{
public void run()
{
if(i<alBmps.size())
{
iv.setImageBitmap(alBmps.get(i));
}
else
{
i=0;
iv.setImageBitmap(alBmps.get(i));
}
i++;
}
};