我有一个类似这样的布局。
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 - 然后您可以使用以下代码动态更改布局的背景
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);
}
}
这是日志跟踪
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)
我想尝试的是在 Activity 时自动更改它。
最佳答案
onCreate()
仅在 Activity 首次打开时调用一次。离开后,onPause()
会被调用,稍后当您返回 Activity 时,onResume()
会被调用。
因此,要在每次导航到 Activity 时更改背景,请将代码从 onCreate()
更改为 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);
}}
关于android - 动态自动更改布局背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20795012/