How to keep changing the background image non stop?

时间:2017-08-05 11:15:20

标签: android

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

}
};

1 个答案:

答案 0 :(得分:1)

只需在run()方法中调用handler.postDelayed再次启动它,然后像这样修改你的代码:

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