旋转设备时如何获取当前图像

时间:2015-07-14 20:01:53

标签: android slideshow oncreate

我有一个简单的幻灯片,通过点击更改图像。旋转设备时,oncreate功能会重置幻灯片,并从image0开始。如何获得当前形象?

这是我的鳕鱼:

 private int currentImage = 0;
private int numImages = 5;
int[] imageList = { R.drawable.pic1, R.drawable.pic2, R.drawable.pic3, R.drawable.pic4, R.drawable.pic5};
@Override
protected void onCreate(Bundle savedInstanceState) {
    currentImage = savedInstanceState.getInt("currentImage");
    savedInstanceState.getBundle()
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final ImageView image = (ImageView) findViewById(R.id.imageView);
    image.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          currentImage++;
            currentImage = currentImage % numImages;
            image.setImageResource(imageList[currentImage]);
        }
    });

}

3 个答案:

答案 0 :(得分:2)

使用onSaveInstanceState将您的计数器保存到Bundle。该捆绑包实例将被推送到onCreate方法。

答案 1 :(得分:1)

您的解决方案

private int currentImage = 0;
private int numImages = 5;
int[] imageList = { R.drawable.pic1, R.drawable.pic2, R.drawable.pic3, R.drawable.pic4, R.drawable.pic5};
ImageView image;
private static final String IMAGE_COUNTER_KEY = "image_counter_key";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    image = (ImageView) findViewById(R.id.imageView);
    if (savedInstanceState != null) {
        currentImage = savedInstanceState.getInt(IMAGE_COUNTER_KEY);
        setCurrentImage(currentImage);
    }
    image.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            currentImage++;
            setCurrentImage(currentImage);
        }
    });

}
//In your activity override the onSavedInstanceState()
@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
        outState.putInt(IMAGE_COUNTER_KEY, currentImage);
    }
}

//This is a helper method for setting the image based on your code
private void setCurrentImage(int imageNumber) {
        currentImage = currentImage % numImages;
        image.setImageResource(imageList[currentImage]);
}

答案 2 :(得分:0)

var size = cc.Director.getInstance().getWinSize();