[单击按钮时如何更改布局的背景图像

问题描述 投票:0回答:2

如何使用一个按钮更改布局的背景图像。

我知道如何为布局背景设置一幅图像,但是如何在两幅或更多图像之间切换?我想我将必须创建图像数组

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);
        }
        });

例如:当您单击“等于”按钮时,计算器中的背景应该切换]

我按下等号按钮

enter image description here

并且背景从菲奥娜的图片变成史莱克enter image description here

java android onclicklistener
2个回答
0
投票

尝试此操作以在两个图像之间切换

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


0
投票

要显示图像的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 ListenerButton中,您只需要从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.
  }
© www.soinside.com 2019 - 2024. All rights reserved.