how to display image in imageview from gallery, in fragment?

爱⌒轻易说出口 提交于 2020-01-03 04:22:07

问题


I tried to get image from gallery and capture from camera and display image in my imageView using fragment but the onActivityResult() does not response. Below is my code for capturing image from camera or gallery.

final CharSequence[] items = { "Take Photo", "Choose from Library",
            "Cancel" };

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle("Add Photo!");
    builder.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int item) {
            if (items[item].equals("Take Photo")) {
                final Intent intent = new Intent(
                        MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
                startActivityForResult(intent, CAPTURE_IMAGE);
            } else if (items[item].equals("Choose from Library")) {

                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, ""),
                        PICK_IMAGE);
            } else if (items[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }
    });
    builder.show();
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    System.out.println("OnActivityResult Call");
    if (resultCode != Activity.RESULT_CANCELED) {
        if (requestCode == PICK_IMAGE) {
            imagePath = getAbsolutePath(data.getData());
            myImageView.setScaleType(ImageView.ScaleType.FIT_XY);
            imageLoader.displayImage("file://" + imagePath, ivUpload,
                    options);
        } else if (requestCode == CAPTURE_IMAGE) {
            imagePath = getImagePath();
            System.out.println("IMAGE PATH===" + imagePath);
            myImageView.setScaleType(ImageView.ScaleType.FIT_XY);
            imageLoader.displayImage("file://" + imagePath, ivUpload,
                    options);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

}

private String getAbsolutePath(Uri uri) {
    String[] projection = { MediaColumns.DATA };
    @SuppressWarnings("deprecation")
    Cursor cursor = getActivity().managedQuery(uri, projection, null, null,
            null);
    if (cursor != null) {
        int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } else
        return null;
}

private Uri setImageUri() {
    File file = new File(Environment.getExternalStorageDirectory()
            + "/DCIM/", "image" + new Date(CAPTURE_IMAGE).getTime()
            + ".png");
    Uri imgUri = Uri.fromFile(file);
    this.imagePath = file.getAbsolutePath();
    return imgUri;
}

private String getImagePath() {
    return imagePath;
}

please give me any solution for that fragment. i also try with in activity. it is work but in fragment does not upload image from gallery.


回答1:


If you have Image path, you can directly display image from image path..

You can write like this...

 imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

BitmapFactory.decodeFile() method allows you to decode image from file path. so you can set decoded image directly to the ImageView by setImageBitmap() method.

Edit :

Here I am adding sample code for picking intent..
You can take reference and see whats the problem there..

To Call Image Intent

Intent i = new Intent(Intent.ACTION_PICK,
        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(i, RESULT_LOAD_IMAGE);

Activity Result

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 = context.getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);

            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            img_user.setImageBitmap(BitmapFactory.decodeFile(picturePath));
            btn_set.setEnabled(true);
            cursor.close();
        } else {
            Toast.makeText(getActivity(), "Try Again!!", Toast.LENGTH_SHORT)
                    .show();
        }

}

This may help you..




回答2:


That fragment does the job

public class ClientFormFragment extends Fragment {
public static final String TAG = "Test";

private ScrollView mScrollView;
private LinearLayout mFormView;

private static int RESULT_LOAD_IMAGE = 1;
Uri myPicture = null;
Button buttonLoadImage;


private static int sId = 0;

private static int id() {
    return sId++;
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    Log.d(TAG, "onAttach(): activity = " + activity);
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d(TAG, "onCreate(): savedInstanceState = " + savedInstanceState);
    setRetainInstance(true);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    Log.d(TAG, "onCreateView(): container = " + container
            + "savedInstanceState = " + savedInstanceState);

    if (mScrollView == null) {
        // normally inflate the view hierarchy
        mScrollView = (ScrollView) inflater.inflate(R.layout.bmr__fragment_client_form,container, false);
        mFormView = (LinearLayout) mScrollView.findViewById(R.id.form);

        buttonLoadImage = (Button) mScrollView.findViewById(R.id.select);

        buttonLoadImage.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {

                Intent i = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                startActivityForResult(i, RESULT_LOAD_IMAGE);
            }
        });


    } else {

        ViewGroup parent = (ViewGroup) mScrollView.getParent();
        parent.removeView(mScrollView);
    }
    return mScrollView;
}


@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMAGE  && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        Cursor cursor = getActivity().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) mFormView.findViewById(R.id.imageView);
        imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

    }


}


@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    Log.d(TAG, "onActivityCreated(): savedInstanceState = "
            + savedInstanceState);

}

@Override
public void onDestroyView() {
    super.onDestroyView();
    Log.d(TAG, "onDestroyView()");
}

@Override
public void onDestroy() {
    super.onDestroy();
    Log.d(TAG, "onDestroy()");
}

@Override
public void onDetach() {
    super.onDetach();
    Log.d(TAG, "onDetach()");
}



public void onLoadFinished(Loader<Void> id, Void result) {
    Log.d(TAG, "onLoadFinished(): id=" + id);
}

public void onLoaderReset(Loader<Void> loader) {
    Log.d(TAG, "onLoaderReset(): id=" + loader.getId());
}



}

With that XML

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/scroll_view"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true"
    android:isScrollContainer="false">

    <LinearLayout
        android:id="@+id/form"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center"
        android:orientation="vertical"
        android:weightSum="1">

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingTop="20px">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingLeft="10px"
                android:paddingTop="20px"
                android:text="Name" />

            <EditText
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="0.50"
                android:paddingTop="20px" />


        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingTop="20px">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="City"
                android:paddingTop="20px"
                android:paddingLeft="10px" />

            <EditText
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="0.50"
                android:paddingTop="20px" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingTop="20px">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Zip code"
                android:paddingTop="20px"
                android:paddingLeft="10px" />

            <EditText
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="0.50"
                android:paddingTop="20px"
                android:inputType="number" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingTop="20px">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Address"
                android:paddingTop="20px"
                android:paddingLeft="10px" />

            <EditText
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="0.50"
                android:paddingTop="20px" />

        </LinearLayout>


        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingTop="20px">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Notes"
                android:paddingTop="20px"
                android:paddingLeft="10px" />

            <EditText
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:inputType="textLongMessage"
                android:layout_weight="0.50"
                android:paddingTop="20px" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingTop="20px">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Status"
                android:paddingTop="20px"
                android:paddingLeft="10px" />

            <RadioGroup
                android:id="@+id/radioStatus"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <RadioButton
                    android:id="@+id/radioAccepted"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Accepted"
                    android:checked="true" />

                <RadioButton
                    android:id="@+id/radioWaiting"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Waiting" />

                <RadioButton
                    android:id="@+id/radioRefused"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Refused" />

            </RadioGroup>

        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingTop="20px">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Pictures"
                android:paddingTop="20px"
                android:paddingLeft="10px" />

            <Button
                android:id="@+id/select"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingTop="20px"
                android:text="Select" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingTop="20px">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/imageView"
                />

        </LinearLayout>


        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:paddingTop="20px"
            android:text="Create" />
    </LinearLayout>
</ScrollView>



回答3:


u can set image from gallery

private static int RESULT_LOAD_IMAGE = 1;

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
            buttonLoadImage.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {

                    Intent i = new Intent(
                            Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                    startActivityForResult(i, RESULT_LOAD_IMAGE);
                }
            });
        }


        @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));

            }


        }



回答4:


Override onActivityResult in activity.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

        fragment.onActivityResult(requestCode, resultCode, data);

}


来源:https://stackoverflow.com/questions/25759227/how-to-display-image-in-imageview-from-gallery-in-fragment

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!