我有以下代码。我从片段中的库中将图像设置为ImageView。问题是当我更改片段并再次使用ImageView返回片段时,它具有默认图像,而不是我设置的图像。
pattern
我有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);
}
}
}
方法将选定的图像保存到位图,onSaveInstanceState
方法将图像设置回ImageView,当我回到Fragment时。但这不起作用。有帮助吗?
提前致谢
答案 0 :(得分:1)
这是因为你的片段根据Fragments Lifecycle丢失了它的视图。要解决您的问题,请执行下一步操作:
创建全局变量private Uri mSelectedImageUri
;
使用此变量代替您的本地Uri selectedImageUri
:
if (requestCode == SELECT_PICTURE) {
mSelectedImageUri = data.getData();
selectedImagePath = getPath(mSelectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
img.setImageURI(mSelectedImageUri);
}
在此行img = (ImageView)rootView.findViewById(R.id.userImage);
下面添加检查:
if (mSelectedImageUri != null) {
img.setImageURI(mSelectedImageUri);
}