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
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
private int[] images; // declare your array in global scope
private int imagesIndex = 0;
Then you need to populate your Array
with Drawable Resources
. You can do it in onCreate() method
(if using Array
in `Activity).
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
.
@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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.