如何保存ImageButton的状态

时间:2011-11-24 13:15:32

标签: android

我正在尝试在savedInstanceState中保存ImageButton的路径,以免丢失图像以旋转手机。但是只有一次它在路径值i等于null(path == null)

之后工作
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentLayout(R.layout.contact_information_wga800);

    if (savedInstanceState != null) {
        String profilefirstname = savedInstanceState.getString("firstname");
        firstname.setText(profilefirstname);
        String profilepath=savedInstanceState.getString("path");
        if(profilepath !=null){
            imagebutton.setImageBitmap( BitmapFactory.decodeFile(profilepath));
        }
    }

@Override
public void onSaveInstanceState(Bundle savedInstanceState)
{
    savedInstanceState.putString("firstname", firstname.getText().toString());
    savedInstanceState.putString("path", media_path);
    super.onSaveInstanceState(savedInstanceState);
}

当我使用相机或android画廊设置imagebutton位图时,这是一个部分。

switch(requestCode) {
    case REQUEST_CAMERA:
        if (resultCode == RESULT_OK) {
            final Bundle extras = data.getExtras();
            bmp = (Bitmap)extras.get("data");
            if( bmp != null ) {
                final File f = this.getFileStreamPath("ping_media.jpg");
                if (f.exists()) { 
                    f.delete();
                }
                try {
                    final FileOutputStream out = this.openFileOutput("ping_media.jpg",MODE_PRIVATE);
                    bmp.compress(CompressFormat.JPEG, 12, out);
                    out.close();
                    media_path = f.getAbsolutePath();
                    if(dm.densityDpi>=200) {
                        contactimg.setImageBitmap(getRoundedCornerBitmap(getResizedBitmap(bmp, 72, 72), 72));
                    } else if(dm.densityDpi>130 && dm.densityDpi<200) {
                        contactimg.setImageBitmap(getRoundedCornerBitmap(getResizedBitmap(bmp, 48, 48), 48));
                    } else {
                        contactimg.setImageBitmap(getRoundedCornerBitmap(getResizedBitmap(bmp, 32, 32), 32));
                    }                               
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        break ;
    case REQUEST_SELECT_PHOTO:
        if( resultCode != 0 ) {
            final Cursor c = managedQuery(data.getData(),null,null,null,null);
            if (c.moveToFirst()) {
                media_path = c.getString(1);
                bmp = BitmapFactory.decodeFile(media_path);
                contactimg.setImageBitmap(getRoundedCornerBitmap( getResizedBitmap(bmp, 48, 48), 48));
            }
        }
        break;
}

我应该这样做,所以在任何时候旋转手机我都没有丢失图像按钮的位图。

1 个答案:

答案 0 :(得分:0)

您似乎正在使用成员变量media_path来存储路径。在onCreate中再次读取Bundle中的路径时,需要更新此成员。否则,当您尝试将其保存在onSaveInstanceState中时,它仍为null(除非您的开关块已经同时运行)。