Android:从SD卡中选择一个图像并将其显示在Fragment中

时间:2013-02-15 23:01:03

标签: android-layout android-intent

我正在使用片段(API 4.1),我想让用户按下按钮,访问他/她的图库,选择图像,并让该图像在按钮出现的原始片段上显示图像视图。我正在使用以下代码:

public class FillBox1Frag extends Fragment {
Button addPics, placeBox;
ImageView imgView;
Bitmap b;
Uri photoUri;
LinearLayout fillBoxLayout;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    if (container == null) {
        return null;
    }

    fillBoxLayout = (LinearLayout) inflater.inflate(R.layout.fillbox1_frag,
            container, false);
    newBin = new Bin();
    addPics = (Button) fillBoxLayout.findViewById(R.id.bPics);
    imgView = (ImageView) fillBoxLayout.findViewById(R.id.imageView1);
    addPics.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub

            Intent picChooser = new Intent(Intent.ACTION_GET_CONTENT,
                    MediaStore.Images.Media.INTERNAL_CONTENT_URI);
            picChooser.setType("image/*");
            startActivityForResult(picChooser, 12345);
        }
    });
    return fillBoxLayout;
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
    case 12345:
        if (resultCode == 12345) {
            photoUri = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = FillBox1Frag.this.getActivity()
                    .getContentResolver()
                    .query(photoUri, filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex);
            cursor.close();
            b = BitmapFactory.decodeFile(filePath);
            imgView.setImageBitmap(b);
        }
    }
}

我访问了Gallery,但在选择时,它只返回到原始片段,并且不显示图像。这是我的XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fillbox"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:tag="fillbox" >

<Button
    android:id="@+id/bPics"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="89dp"
    android:background="@drawable/buttonpics" />

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

我找到了很多处理类似问题的答案,但没有任何能够帮助我如何使用片段创建这个过程。有关如何让我选择的图像出现在ImageView中的任何想法?谢谢你的帮助!

0 个答案:

没有答案