我在片段和FAB上使用了对话框单击,当我从库中选择图像但是所选图像无法将其设置为图像视图。 我的查询是如何在对话框中设置所选图像?
如何在我的片段中使用onActivityResult()
?
提前致谢!!
这是我的代码..
public class PizzasFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_pizza, container, false);
fab = (FloatingActionButton) rootView.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Dialog addDish = new Dialog(getActivity());
addDish.requestWindowFeature(Window.FEATURE_NO_TITLE);
addDish.setContentView(R.layout.main_layout);
imageDish = (ImageView) addDish.findViewById(R.id.IMGFood);
imageDish.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, SELECT_PICTURE);
} catch (Exception e) {
Toast.makeText(getActivity(),
"Select Image From Gallery", Toast.LENGTH_LONG)
.show();
// TODO: handle exception
}
}
});
return rootView;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data != null) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContext().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
imageDish.setImageBitmap(BitmapFactory.decodeFile(picturePath));
imageDish.setEnabled(true);
Log.d("picturepath",""+picturePath);
cursor.close();
} else {
Toast.makeText(getActivity(), "Try Again!!", Toast.LENGTH_SHORT)
.show();
}
}
答案 0 :(得分:0)
尝试使用onActivityResult
的代码@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}