单击按钮更改图像

时间:2019-03-05 19:15:56

标签: java android

iam是android开发的新手,这里iam试图在单击按钮时更改图像,iam使用animate()方法淡出其中一张图像并获得结果。第一次单击按钮会使图像褪色,但是第二次我单击此按钮,它没有任何结果(图像不会褪色)。

请给我任何可能的解决方案。谢谢

.java文件

!command

xml文件

package e.nani.bestimage;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

public void change(View view) {
    int flag=0;
    ImageView img1 = (ImageView) findViewById(R.id.single);
    ImageView img2 = (ImageView) findViewById(R.id.withands);
    switch(flag){

    case 0:img1.animate().alpha(0f).setDuration(2000);
                img2.animate().alpha(1f).setDuration(2000);
                flag=1;
                break;
        case 1:    img1.animate().alpha(1f).setDuration(2000);
            img2.animate().alpha(0f).setDuration(2000);
            flag=0;
            break;
    }
    }
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ImageView img1=(ImageView) findViewById(R.id.single);
    ImageView img2=(ImageView) findViewById(R.id.withands);
    img1.animate().alpha(1f).setDuration(2000);
    img2.animate().alpha(0f).setDuration(2);

}

}

1 个答案:

答案 0 :(得分:1)

每当调用change()方法时,它将标志设置为0。尝试以下操作:

public class MainActivity extends AppCompatActivity {

int flag;
public void change(View view) {

ImageView img1 = (ImageView) findViewById(R.id.single);
ImageView img2 = (ImageView) findViewById(R.id.withands);
switch(flag){

  case 0:
            img1.animate().alpha(0f).setDuration(2000);
            img2.animate().alpha(1f).setDuration(2000);
            flag=1;
            break;
    case 1:   
        img1.animate().alpha(1f).setDuration(2000);
        img2.animate().alpha(0f).setDuration(2000);
        flag=0;
        break;
  }
}
 @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
   flag = 0;
   ImageView img1=(ImageView) findViewById(R.id.single);
   ImageView img2=(ImageView) findViewById(R.id.withands);
   img1.animate().alpha(1f).setDuration(2000);
   img2.animate().alpha(0f).setDuration(2);

 }

 }