开发者

ImageView disapears when changing to portrait/landscape

I have an imageview with a bitmap picture on it. i set this picture in the onActivityResault. the problem is when i change to portrait/landscape the image disapears.

protected void onActivityResult(int requestCode,int resultCode, Intent imageRe开发者_Python百科turnedIntent) { 
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 

    switch(requestCode) { 
    case 1:
        if(resultCode == RESULT_OK){  
            Uri selectedImage = imageReturnedIntent.getData();
            InputStream imageStream;
            try {
                imageStream = getContentResolver().openInputStream(selectedImage);
                Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
                image.setImageBitmap(yourSelectedImage);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }


When orientation changes activity is destroyed and created again. If you're creating your layout using xml all widgets having @id set, should be automatically recreated with it's content. Otherwise you have to do that manually - take a look at Activity's methods onRestoreInstanceState() onSaveInstanceState() just override them and write your own save/restore code. Some of untested code, hope, that it will give you an idea:

@Override
public void onSaveInstanceState(Bundle b){
    b.putParcelable("image", image.getBitmap());
}

@Override
public void onRestoreInstanceState(Bundle b){
    //you need to handle NullPionterException here.
    image.setBitmap((Bitmap) b.getParcelable("image"));
}


If you give an ID to your imageview it won't be disappear, when you change orientation. I think it's the easiest way, to keep, your view.


Building off piotrpo's answer, here is a more specific version:

@Override
public void onSaveInstanceState(Bundle b){
    b.putParcelable("image", imageMap);
}

@Override
public void onRestoreInstanceState(Bundle b){
    imageMap = b.getParcelable("image");
    imageView.setImageBitmap(imageMap);
}

where imageMap is your bitmap image

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜