如何在图片库中以图片形式显示图片?

时间:2014-09-10 07:05:01

标签: android gallery

我尝试从图库中获取图像并从相机捕获并使用片段在我的imageView中显示图像,但onActivityResult()没有响应。下面是我从相机或图库中捕获图像的代码。

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;
}

请给我任何有关该片段的解决方案。我也尝试过活动。这是工作,但在片段中不会从图库上传图像。

4 个答案:

答案 0 :(得分:4)

该片段完成工作

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());
}



}

使用该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>

答案 1 :(得分:3)

如果您有图像路径,则可以直接显示图像路径中的图像..

你可以这样写......

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

BitmapFactory.decodeFile() 方法允许您从文件路径解码图像。因此,您可以通过ImageView方法将解码图像直接设置为setImageBitmap()

修改:

我在这里添加用于挑选意图的示例代码。
你可以参考一下,看看那里有什么问题..

调用图片意图

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

活动结果

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();
        }

}

这可能对你有帮助..

答案 2 :(得分:3)

你可以从图库中设置图片

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

            }


        }

答案 3 :(得分:0)

在活动中覆盖onActivityResult。

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

        fragment.onActivityResult(requestCode, resultCode, data);

}