[英]How to Change the background Image of a Layout when a button clicked
如何使用一个按钮更改布局的背景图像。
我知道如何为布局背景设置一个图像,但是如何在两个或多个图像之间切换? 我想我必须创建一组图像
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);
}
});
例如:单击“等于”按钮时,计算器中的背景应该会切换
我按下相等按钮
要将图像Array
显示为背景,您需要创建Array
和指向Array
中position
的index
private int[] images; // declare your array in global scope
private int imagesIndex = 0;
然后你需要用Drawable Resources
填充你的Array
。 您可以在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;
最后,在您的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.
}
试试这个在两个图像之间切换
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);
}
}
});
如果您想了解更多,请联系我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.