2

I have a Layout something like this.

xml

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/mylayout" > </RelativeLayout>

java - Then you can dynamically change the background of the layout using below code

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.mylayout);
        int images[] = {R.drawable.image1, R.drawable.image2, R.drawable.image3, R.drawable.image4};

        relativeLayout.setBackgroundResource(images[getRandomNumber()]);
         private Timer myTimer;
         myTimer = new Timer();
         myTimer.schedule(new TimerTask() 
         {          
            @Override
            public void run() 
            {
                TimerMethod();
            }
         }, 0, 9000);
    }

private void TimerMethod()
           {
               new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {

                    //TODO after 9 sec
                     relativeLayout.setBackgroundResource(images[getRandomNumber()]);
                }
            }, 9000);
        }
}

Here is the Log Trace

01-04 01:08:15.307: E/AndroidRuntime(30200): FATAL EXCEPTION: Timer-0
01-04 01:08:15.307: E/AndroidRuntime(30200): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
01-04 01:08:15.307: E/AndroidRuntime(30200):    at android.os.Handler.<init>(Handler.java:121)
01-04 01:08:15.307: E/AndroidRuntime(30200):    at info.androidhive.slidingmenu.LoginActivity.TimerMethod(LoginActivity.java:55)
01-04 01:08:15.307: E/AndroidRuntime(30200):    at info.androidhive.slidingmenu.LoginActivity.access$0(LoginActivity.java:53)
01-04 01:08:15.307: E/AndroidRuntime(30200):    at info.androidhive.slidingmenu.LoginActivity$1.run(LoginActivity.java:48)
01-04 01:08:15.307: E/AndroidRuntime(30200):    at java.util.Timer$TimerImpl.run(Timer.java:284)

what i want to try is to change it automatically while on the activity.

AndroidNewbie
  • 669
  • 3
  • 16
  • 23

7 Answers7

3

onCreate() is called only once, when the Activity is first opened. After you navigate away, onPause() is called and later when you return to the Activity, onResume() is called.

So, to change the background every time you navigate to the Activity, shift your code to change the background from onCreate() to onResume().

public class MainActivity extends Activity {
RelativeLayout relativeLayout;
int images[];
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    relativeLayout = (RelativeLayout) findViewById(R.id.mylayout);
    images[]  = {R.drawable.image1, R.drawable.image2, R.drawable.image3, R.drawable.image4};     
}

protected void onResume()
{
    if(relativeLayout != null)
      relativeLayout.setBackgroundResource(images[getRandomNumber()]);

}

private int getRandomNumber() {
    //Note that general syntax is Random().nextInt(n)
    //It results in range 0-4
    //So it should be equal to number of images in images[] array
    return new Random().nextInt(4);
}}
Swayam
  • 16,294
  • 14
  • 64
  • 102
2

You can do this by making use of Timers and Handlers Try this code:

   public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.mylayout);
        int images[] = {R.drawable.image1, R.drawable.image2, R.drawable.image3, R.drawable.image4};

        relativeLayout.setBackgroundResource(images[getRandomNumber()]);
         private Timer myTimer;
         myTimer = new Timer();
         myTimer.schedule(new TimerTask() 
         {          
            @Override
            public void run() 
            {
                TimerMethod();
            }
         }, 0, 9000);
    }

private void TimerMethod()
           {
               new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {

                    //TODO after 9 sec
                     relativeLayout.setBackgroundResource(images[getRandomNumber()]);
                }
            }, 9000);
        }
}
Zankhna
  • 4,570
  • 9
  • 62
  • 103
0

Try calling your relativeLayout.setBackgroundResource(images[getRandomNumber()]); on your activity's onResume() method like this.

protected void onResume()
{
    if(relativeLayout != null){
          relativeLayout.setBackgroundResource(images[getRandomNumber()]);
    }
}

Hope this helps.

AndyN
  • 1,742
  • 1
  • 15
  • 30
0

In onCreate Method your code will execute only once and if you want it to change after some time interval then use TimerTask or you can use Handler also.

Jitesh Dalsaniya
  • 1,917
  • 3
  • 20
  • 36
0

first create transition_drawable.xml in drawable res

<transition xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:drawable="@drawable/one"/>
 <item android:drawable="@drawable/two"/>
 <item android:drawable="@drawable/three"/>

`

and in your layout`

android:background="@drawable/transition_drawable"

and in your activity.java

int DrawableImage[] = {R.drawable.one , R.drawable.two, R.drawable.three};
final Handler handler = new Handler();
    final int[] i = {0};
    final int[] j = {1};
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Resources res = getApplicationContext().getResources();
                    TransitionDrawable out = new TransitionDrawable(new Drawable[]{res.getDrawable(DrawableImage[i[0]]), res.getDrawable(DrawableImage[j[0]])});
                    out.setCrossFadeEnabled(true);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                        yourlayout.setBackground(out);
                    }
                    out.startTransition(2000);
                    i[0]++;
                    j[0]++;
                    if (j[0] == DrawableImage.length) {
                        j[0] = 0;
                    }
                    if (i[0] == DrawableImage.length) {
                        i[0] = 0;
                    }
                    handler.postDelayed(this, 4000);
                }
            });
        }
    }, 0);
Rupesh K.C
  • 41
  • 6
0

I made it work Like this:

private int[] backgroundImages = {R.drawable.bg1, R.drawable.bg2, R.drawable.bg3, R.drawable.bg4};
RelativeLayout background = findViewById(R.id.background);
background.setBackgroundResource(backgroundImages[new Random().nextInt(4)]);
Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                @Override
                public void run() {
                    background.setBackgroundResource(backgroundImages[new Random().nextInt(4)]);
                }
            }, 3000);
        }
    }, 0, 3000);
M Umer
  • 353
  • 6
  • 13
-1

I know this old question but I will post my answer for others you can use the following code

public class myActivity extends AppCompatActivity {

    RelativeLayout relativeLayout;
    int images[];

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.myactivity);

        relativeLayout = (RelativeLayout) findViewById(R.id.mylayout);
        images  = new int[{R.drawable.fighter3,R.drawable.sky,R.drawable.yellow_bullet,R.drawable.chicken3};

        //Create the timer object which will run the desired operation on a schedule or at a given time
        Timer timer = new Timer();

        //Create a task which the timer will execute.  This should be an implementation of the TimerTask interface.
        //I have created an inner class below which fits the bill.
        MyTimer mt = new MyTimer();

        //We schedule the timer task to run after 1000 ms and continue to run every 1000 ms.
        timer.schedule(mt, 1000, 1000);

    }

    private int getRandomNumber() {
        //Note that general syntax is Random().nextInt(n)
        //It results in range 0-4
        //So it should be equal to number of images in images[] array
        return new Random().nextInt(4);
    }

    class MyTimer extends TimerTask {

        public void run() {

            //This runs in a background thread.
            //We cannot call the UI from this thread, so we must call the main UI thread and pass a runnable
            runOnUiThread(new Runnable() {

                public void run() {
                    Random rand = new Random();
                    //The random generator creates values between [0,256) for use as RGB values used below to create a random color
                    //We call the RelativeLayout object and we change the color.  The first parameter in argb() is the alpha.
                    relativeLayout.setBackgroundResource(images[getRandomNumber()]);
                }
            });
        }
    }
}