【发布时间】:2014-01-03 12:19:33
【问题描述】:
假设你有一个类似这样的Layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/mylayout" >
//Other view elements like buttons, TextViews
</RelativeLayout>
然后您可以使用以下代码动态更改layout 的background
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 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);
}
}
我如何automatically 使我的背景适应设备的屏幕尺寸?
【问题讨论】:
-
设置宽度和高度属性匹配父级,它会自动适应
标签: android android-layout android-relativelayout