how to get auto changing background image after few seconds? - android

i'm working on an Android application in which i want the background image to be changed after every 5 seconds. i have all the images in my drawable folder.
i am giving the code which i am using but i am not getting the output. As an output i am getting a still image which is not changing.
Please help
Thanks
[CODE]
public class Home extends Activity {
public static int count=0;
int[] drawablearray=new int[]{R.drawable.slider_1,R.drawable.slider_2,R.drawable.slider_3,R.drawable.slider_4,R.drawable.slider_5};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
new Handler().postDelayed(new Runnable() {
public void run() {
if(count<drawablearray.length){
Home.this.getWindow().
setBackgroundDrawableResource(drawablearray[count]);
count++; //<<< increment counter here
}
else{
// reset counter here
count=0;
}
}
}, 5000);
}
}

You can achieve this using Timer
public class Home extends Activity {
public static int count=0;
int[] drawablearray=new int[]{R.drawable.slider_1,R.drawable.slider_2,R.drawable.slider_3,R.drawable.slider_4,R.drawable.slider_5};
Timer _t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
lnMain = (LinearLayout) findViewById(R.id.lnMain);
_t = new Timer();
_t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() // run on ui thread
{
public void run() {
if (count < drawablearray.length) {
lnMain.setBackgroundDrawable(drawablearray[count]);
count = (count + 1) % drawablearray.length;
}
}
});
}
}, 5000, 5000);
}
}

Why don't you have a look at the ViewFlipper class
http://developer.android.com/reference/android/widget/ViewFlipper.html

final Handler h = new Handler();
Runnable r = new Runnable() {
public void run() {
Home.this.getWindow().setBackgroundDrawableResource(drawablearray[count]);
count += (count+1)%drawablearray.length; //<<< increment counter here
h.postDelayed(this, 5000);
}
};
now call like
h.postDelayed(r, 5000);

I think that would be easier to work with the xmls. You can change the background of the main layout of the activity.
Try something like this:
public class Home extends Activity {
public static int count=0;
int[] drawablearray=new int[]{R.drawable.slider_1,R.drawable.slider_2,R.drawable.slider_3,R.drawable.slider_4,R.drawable.slider_5};
LinearLayout ll;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
ll = (LinearLayout) findViewByID(R.id.mainlayout) //It depends of the name that you gave to it
new Handler().postDelayed(new Runnable() {
public void run() {
ll.setBackgroundDrawable(drawablearray[count]);
// or ll.setBackgroundResource(resid) if you want.
count += (count+1)%drawablearray.length;
}
}, 5000);
}
}

Related

How to schedule different images to change in design background

I'm currently working on a weather project in Android Studio where I want to schedule image changes in my design background every 5 seconds, I have all the image resources in my #drawable directory. I watched a basic tutorial where they explained some things in the demo but it only helped a little and didn't quite suit me, I'm still confused because I'm getting a lot of errors but I've currently tried these few codes:
HomeActivity.java:
public class HomeActivity extends AppCompatActivity {
public static int count=0;
int[] drawablearray=new int[]{R.drawable.burj_khalifa,R.drawable.central_bank_of_nigeria,R.drawable.eiffel_tower,R.drawable.hong_kong,R.drawable.statue_of_liberty};
Timer _t;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
imageView = findViewById(R.id.imageView);
ImageView = (ConstraintLayout) findViewById(R.id.lnMain);
_t = new Timer();
_t.scheduleAtFixedRate(new TimerTask); {
public void run(); {
runOnUiThread(new Runnable() { // run on ui thread
#Override
public void run() {
if (count < drawablearray.length) {
lnMain.setBackgroundDrawable(drawablearray[count]);
count = (count + 1) % drawablearray.length;
}
}
});
}
}, 5000, 5000);
}
}
Any Idea on how to Organize it to suit the design?
final Handler h = new Handler();
Runnable r = new Runnable() {
public void run() {
Home.this.getWindow.setBackgroundDrawableResource(drawableArray[count]);
cout += (count + 1) % drawableArray.length;
h.postDelayed(this, 5000);
}
};
final Runnable r = new Runnable() {
public void run() {
imageView.setBackgroundDrawableResource(drawablearray[count]);
count += (count+1)%(drawablearray.length);
handler.postDelayed(this, 5000);
}
};
And the call is like this:
handler.postDelayed(r,0);
This will call the runnable to execute and handle.postDelayed will run the method every 5000 millsec.
I already fixed the error by using constraintlayout in place of imageview and inmain. I also got id for the layout:
constraintLayout = findViewById(R.id.layout);
constraintLayout.setBackgroundResource(R.drawable.burj_khalifa);
_t = new Timer();
_t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() { // run on ui thread
#Override
public void run() {
if (count < drawable.length) {
constraintLayout.setBackgroundResource(drawable[count]);
count = (count + 1) % drawable.length;
}
}
});
}
}, 5000, 5000);
}
}

How to keep changing the background image non stop?

I wrote code which can change the background every 3 second, but unfortunately it only change 1 time, I try using the count but it wont work, where did it went wrong?
public class MainActivity extends AppCompatActivity {
public static int count=0;
int images[] = new int[] {R.drawable.main, R.drawable.main2, R.drawable.main3, R.drawable.main4};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Handler().postDelayed(new Runnable() {
public void run() {
if (count < images.length) {
RelativeLayout background = (RelativeLayout) findViewById(R.id.activity_main);
Random rand = new Random();
int index = rand.nextInt(images.length);
background.setBackgroundResource(images[index]);
count++;
}
else{
count = 0;
}
}
}, 3000);
}
};
Just call handler.postDelayed inside run() method to start it again, and modify your code like this:
public class MainActivity extends AppCompatActivity {
int images[] = new int[] {R.drawable.main, R.drawable.main2, R.drawable.main3, R.drawable.main4};
final Handler animHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout background = (RelativeLayout) findViewById(R.id.activity_main);
animHandler.post(new Runnable() {
#Override
public void run() {
Random rand = new Random();
int index = rand.nextInt(images.length);
background.setBackgroundResource(images[index]);
animHandler.postDelayed(this, 3000);
}
});
}
};
}

Counter in loop

How to do sample counter in Activity? This is not working.
public class MainActivity extends AppCompatActivity implements Runnable {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
run();
}
#Override
public void run() {
while (true) {
updateTv();
try {
Thread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void updateTv() {
int counter = 100;
final TextView tv = (TextView) findViewById(R.id.tv);
tv.setText(String.valueOf(counter));
counter--;
}
}
In onCreate() you're starting an infinite loop inside of the UI thread, blocking it completely. Alternatively you could use a Handler for periodic updates. Maybe using a bigger delay and stop it sometime.
public class MainActivity extends AppCompatActivity implements Runnable {
private final Handler mHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
run();
}
#Override
public void run() {
updateTv();
mHandler.postDelayed(this, 17);
}
public void updateTv() {
int counter = 100;
final TextView tv = (TextView) findViewById(R.id.tv);
tv.setText(String.valueOf(counter));
counter--;
}
}
Anyway you should read What is the Android UiThread (UI thread) for sure.
Consider using Timer class which allows you to define a callback method that will be invoked at specified rate.
An example that fits your needs:
public class CounterActivity extends AppCompatActivity {
private TextView mCounterTextView;
private Timer mTimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_counter);
mCounterTextView = (TextView) findViewById(R.id.counterTextView);
mTimer = new Timer();
mTimer.scheduleAtFixedRate(
new CounterTask(100), 0, TimeUnit.SECONDS.toMillis(1));
}
protected class CounterTask extends TimerTask {
protected int mCounter;
CounterTask(int initial) {
mCounter = initial;
}
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
mCounterTextView.setText(String.valueOf(mCounter));
}
});
--mCounter;
}
}
}
One more thing that should be noticed. As Timer executes it's own thread - it prevents you from updating your UI from outside of the main thread. In that case
you have to register a Runnable using runOnUiThread method.
Also, calling findViewById in a loop is not the best idea.

Android - Changing background every 5 seconds

I have this code in an attempt to have my app change it's background every 5 seconds, however, it only displays the first image in my array. Is there a simple tweak to this I can make so it will run through the 5 different images continuously??
Here is what I have in my MainActivity.class
int count=0; //outside oncreate
//all that is below is within oncreate
final int[] drawablearray=new int[]{R.drawable.one,R.drawable.two,R.drawable.three,R.drawable.four,R.drawable.five};
new Handler().postDelayed(new Runnable() {
public void run() {
if(count<drawablearray.length){
MainActivity.this.getWindow().
setBackgroundDrawableResource(drawablearray[count]);
count++;
}
else{
count=0;
}
}
}, 5000);
Thanks for all and any help!!
You need to call the method recursivly. The way you have currently set it up you only call it once.
int count =0;
boolean abort;
onResume(){
super.onResume();
abort = false;
this.changeBackground(count);
}
onPause(){
abort = true;
super.onPause();
}
private void changeBackground(int count){
if (abort)
return;
new Handler().postDelayed(new Runnable() {
public void run() {
if(count<drawablearray.length){
count++;
}
else{
count=0;
}
changeBackgroundColor(count);
changeBackground(count);
}
}, 5000);
}
private void changeBackgroundColor(int count){
if (abort)
return;
MainActivity.this.getWindow().
setBackgroundDrawableResource(drawablearray[count]);
}
Spin in an infinite loop. Also, you can remove the if-else condition with %:
while (changeBackground == true)
{
new Handler().postDelayed(new Runnable() {
public void run() {
MainActivity.this.getWindow().
setBackgroundDrawableResource(drawablearray[count]);
count = (count + 1) % drawablearray.length;
}, 5000);
}
PS: You may want to configure background change from some event, like on Event e, background changing should stop. One example of such event may be switching from one activity to other. You can achieve this by setting/resetting variable changeBackground.
int count=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//all that is below is within oncreate
final int[] drawablearray=new int[]{R.drawable.one,R.drawable.two,R.drawable.three,R.drawable.four,R.drawable.five};
gettingBackground(drawablearray);
}
private void gettingBackground(final int[] drawablearray) {
// TODO Auto-generated method stub
new Handler().postDelayed(new Runnable() {
public void run() {
if(count<drawablearray.length){
LoginAct.this.getWindow().
setBackgroundDrawableResource(drawablearray[count]);
count++;
gettingBackground(drawablearray);
}
else{
count=0;
}
}
}, 5000);
}

how to change images on imageView after some interval

I have a problem that I want to paste images on ImageView in Android and that images are periodically changed after some interval. Means one by one images shown in ImageView. I am doing this with the help of Thread in java but I got some problem that Thread is not attached and something. Please review my code given below and tell me the exact error and how to remove that error or give me some diffrent way for doing this.
package com.ex.thread;
import com.ex.thread.R;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
public class thread extends Activity implements Runnable{
/** Called when the activity is first created. */
public static Integer[] mThumbIds = {
R.drawable.al1,R.drawable.al2,R.drawable.al3,R.drawable.al4,
};
Thread th;
ImageView iv;
public void run()
{
for(int i=0;i<3;i++)
{
iv.setImageResource(mThumbIds[i]);
System.out.println("Sanat Pandey");
try{
Thread.sleep(3000);
}catch(Exception e)
{
System.out.println(e);
}
}
}
public void create()
{
Thread th = new Thread(new thread());
th.start();
try{
Thread.sleep(3000);
}catch(Exception e)
{
System.out.println(e);
}
}
#Override
public void onCreate(Bundle savedInstace)
{
super.onCreate(savedInstace);
setContentView(R.layout.main);
create();
}
}
Try this..It works out well...
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);``
//
//
int []imageArray={R.drawable.img1,R.drawable.img2,R.drawable.img3};
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
int i=0;
public void run() {
imageView.setImageResource(imageArray[i]);
i++;
if(i>imageArray.length-1)
{
i=0;
}
handler.postDelayed(this, 50); //for interval...
}
};
handler.postDelayed(runnable, 2000); //for initial delay..
}
You can't use things in the UI thread from a background one. So this call:
iv.setImageResource(mThumbIds[i]);
Has to be done in the main thread. In fact you probably don't need a background thread at all to get the effect you're looking for. You can make that just an activity, no need to implement runnable. and then do something like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
iv = (ImageView) findViewById(R.id.yourImageViewID);
int i = 0;
Runnable r = Runnable(){
public void run(){
iv.setImageResource(mThumbIds[i]);
i++;
if(i >= mThumbIds.length){
i = 0;
}
iv.postDelayed(r, 3000); //set to go off again in 3 seconds.
}
};
iv.postDelayed(r,3000); // set first time for 3 seconds
Try this
it's working
public class vv extends Activity {
int b[] = {R.drawable.a, R.drawable.m, R.drawable.b, R.drawable.j, R.drawable.er, R.drawable.chan, R.drawable.vv};
public ImageView i;
int z = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
i = (ImageView) findViewById(R.id.image);
i.setImageResource(b[0]);
Thread timer = new Thread() {
public void run() {
try {
sleep(2000);
for (z = 0; z < b.length + 2; z++) {
if (z < b.length) {
sleep(2000);
runOnUiThread(new Runnable() {
public void run() {
i.setImageResource(b[z]);
}
});
} else {
z = 0;
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("finally");
}
}
};
timer.start();
}
}
try this code.the images was saved in drawable. please do insert a imageview in xml code. noted that the time interval for the following code is 1 sec.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
public ImageView iv;
public static Integer[] mThumbIds = {
R.drawable.pic1,R.drawable.pic2,R.drawable.pic3,R.drawable.pic4};
int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.imageView);
i=0;
t.start();
}
Thread t = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
iv.setImageResource(mThumbIds[i]);
i++;
if(i >= mThumbIds.length){
i = 0;
}}});}}
catch (InterruptedException e) {
}}};
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final int img[] = {R.drawable.flower1, R.drawable.flower2, R.drawable.flower3, R.drawable.flower4};
layout = (RelativeLayout) findViewById(R.id.activity_main);
final Handler handler=new Handler();
Runnable runnable = new Runnable() {
int i = 0;
#Override
public void run() {
layout.setBackgroundResource(img[i]);
i++;
if (i > img.length - 1) {
i = 0;
}
handler.postDelayed(this, 4000); //for interval 4s..
}
};handler.postDelayed(runnable, 100); //for initial delay..
}

Categories

Resources