[英]How to Change the background Image of a Layout when a button clicked
How to change the background image of a layout, using one button.如何使用一个按钮更改布局的背景图像。
I know how to set one image for background of layout, but how to switch between TWO or more image?我知道如何为布局背景设置一个图像,但是如何在两个或多个图像之间切换? I think i will must create a array of images
我想我必须创建一组图像
MainActivity.java 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);
}
});
For example: the background in the calculator should switch when you click the "equal" button例如:单击“等于”按钮时,计算器中的背景应该会切换
i press the equal button我按下相等按钮
and the background changes from the picture of Fiona to Shrek并且背景从菲奥娜的图片变成了史莱克
To show an Array
of images as background, you need to create your Array
, and an index
to point to a position
within your Array
要将图像
Array
显示为背景,您需要创建Array
和指向Array
中position
的index
private int[] images; // declare your array in global scope
private int imagesIndex = 0;
Then you need to populate your Array
with Drawable Resources
.然后你需要用
Drawable Resources
填充你的Array
。 You can do it in onCreate() method
(if using Array
in `Activity).您可以在
onCreate() method
中执行此操作(如果在 `Activity 中使用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;
Finally in Click Listener
of your Button
you simply need to select a resource from your Array
.最后,在您的
Button
的Click Listener
中,您只需要 select 来自您的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.
}
try out this to switch between two images试试这个在两个图像之间切换
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);
}
}
});
If you want to learn more, contact me .如果您想了解更多,请联系我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.