[英]android studio change background image for multiple images
I have 5 images in the drawable folder (bg1, bg2, bg3, bg4, bg5), bg1 is my default background.我在可绘制文件夹中有 5 张图像(bg1、bg2、bg3、bg4、bg5),bg1 是我的默认背景。
I want to change the the image of the background in order eatch time I click the button and when it arrive to the final image it should go again to the first image,我想更改背景图像以获取时间我单击按钮,当它到达最终图像时,它应该再次 go 到第一张图像,
for example if I cliked the button it should set bg2 as background and if I clicked it again it should set bg3 as background and so on,例如,如果我点击按钮,它应该将 bg2 设置为背景,如果我再次点击它,它应该将 bg3 设置为背景,依此类推,
I tried the below code but it only change the background image one time.我尝试了以下代码,但它只更改了一次背景图像。
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
int x = 0;
while(x < 5){
x ++;
// Give image name that you want to show on button click
layout.setBackgroundResource(R.drawable.bg+x);
}
}
});
You have to set x
as a global variable.您必须将x
设置为全局变量。 You set x
in function so it is always 0
.您在 function 中设置x
,因此它始终0
。
int x = 0; //global variable in activity/fragment
...
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
x ++;
x %= 5;
if (x==0) layout.setBackgroundResource(R.drawable.bg1);
else if (x==1) layout.setBackgroundResource(R.drawable.bg2);
else if (x==2) layout.setBackgroundResource(R.drawable.bg3);
else if (x==3) layout.setBackgroundResource(R.drawable.bg4);
else layout.setBackgroundResource(R.drawable.bg5);
}
}
});
Try:尝试:
// declare the varibale globally, or else everytime the onClick is called it will be reset to 0
int x = 1;
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int bg = 0;
// are we larger than 5? lets start again at 1 :)
if (x == 6) x = 1;
if (x == 1) bg = R.drawable.bg1;
if (x == 2) bg = R.drawable.bg2;
if (x == 3) bg = R.drawable.bg3;
if (x == 4) bg = R.drawable.bg4;
if (x == 5) bg = R.drawable.bg5;
layout.setBackgroundResource(bg);
// lets increment you for the next round
x++;
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.