【发布时间】:2015-06-27 18:15:22
【问题描述】:
我有下面的代码。我从片段中的画廊将图像设置为 ImageView。问题是当我更改片段并使用 ImageView 再次返回片段时,它具有默认图像,而不是我设置的图像。
public class Fragment_user extends Fragment {
private static final int SELECT_PICTURE = 1;
private String selectedImagePath=null;
private ImageView img;
@Override
public View onCreateView(
LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.fragment_user, container, false);
//if (savedInstanceState == null){
img = (ImageView)rootView.findViewById(R.id.userImage);
//}else{
//Bitmap bitmap = (Bitmap) savedInstanceState.getParcelable("bitmap");
//img.setImageBitmap(bitmap);
//}
img.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
}
});
return rootView;
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == MainActivity.RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
img.setImageURI(selectedImageUri);
}
}
}
public String getPath(Uri uri)
{
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(uri, projection, null, null, null);
if (cursor == null) return null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String s=cursor.getString(column_index);
cursor.close();
return s;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save the image bitmap into outState
Bitmap bitmap = ((BitmapDrawable)img.getDrawable()).getBitmap();
outState.putParcelable("bitmap", bitmap);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Read the bitmap from the savedInstanceState and set it to the ImageView
if (savedInstanceState != null){
Bitmap bitmap = (Bitmap) savedInstanceState.getParcelable("bitmap");
img.setImageBitmap(bitmap);
}
}
}
当我回到 Fragment 时,我有 onSaveInstanceState 方法将所选图像保存到位图和 onActivityCreated 方法将图像设置回 ImageView。但这不起作用。有什么帮助吗?
提前致谢
【问题讨论】:
标签: android android-fragments android-imageview