如何使用一个按钮更改布局的背景图像。
我知道如何为布局背景设置一幅图像,但是如何在两幅或更多图像之间切换?我想我将必须创建图像数组
MainActivity.java
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LinearLayout view = (LinearLayout) findViewById(R.id.layout1);
view.setBackgroundResource(R.drawable.image);
}
});
例如:当您单击“等于”按钮时,计算器中的背景应该切换]
我按下等号按钮
尝试此操作以在两个图像之间切换
final Switch s = (Switch) findViewById(R.id.switch1);
s.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
if (s.isChecked()){
view.setBackgroundResource(R.drawable.image1);
}else{
view.setBackgroundResource(R.drawable.image2);
}
}
});
如果您想了解更多,请contact me。
要显示图像的Array
作为背景,您需要创建Array
,并创建index
指向position
中的Array
private int[] images; // declare your array in global scope
private int imagesIndex = 0;
然后您需要用Array
填充Drawable Resources
。您可以在onCreate() method
中执行此操作(如果使用“活动”中的Array
。)>
int numOfImages = 4; images = new int[numOfImages]; images[0] = R.drawable.ic_launcher_background; images[1] = R.drawable.ic_launcher_foreground; images[2] = R.drawable.fiona; images[3] = R.drawable.shrek;
最后在
Click Listener
的Button
中,您只需要从Array
中选择一种资源。
@Override
public void onClick(View v) {
LinearLayout view = (LinearLayout) findViewById(R.id.layout1);
view.setBackgroundResource(images[imagesIndex]);
++imagesIndex; // update index, so that next time it points to next resource
if (imagesIndex == images.length - 1)
imagesIndex = 0; // if we have reached at last index of array, simply restart from beginning.
}