【问题标题】:how to display image in imageview from gallery, in fragment?如何在片段中从图库中的图像视图中显示图像?
【发布时间】:2014-09-10 07:05:01
【问题描述】:

我尝试从图库中获取图像并从相机捕获图像并使用片段在我的 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;
}

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

【问题讨论】:

  • 您在从图库中获取图片的片段中遇到什么问题?
  • 当我从图库中选择任何图像时,不会调用 onActivityResult()。为什么?
  • 在片段的父活动中覆盖onActivityResult并在其中调用super.onActivityResult

标签: android gallery


【解决方案1】:

那个片段完成了这项工作

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>

【讨论】:

    【解决方案2】:

    如果你有图片路径,你可以直接从图片路径显示图片..

    你可以这样写……

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

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

    编辑:

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

    调用图像意图

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

    这可能对你有帮助..

    【讨论】:

    • 对不起朋友,我也试试你的答案,但 onActivityResult() 没有打电话。不知道是什么问题。
    • @EleshBaraiya :: 请参阅onActivityResult not being called in Fragment 可能有助于解决问题
    • @Prags 感谢您的回复,但我的问题没有解决。你能回答 onActivityResult() 背后没有在片段中调用的原因吗?
    • imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));也适用于片段..
    【解决方案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));
    
                }
    
    
            }
    

    【讨论】:

    • 抱歉.. 我的问题与 Fragment not in Activity 有关。
    【解决方案4】:

    在活动中覆盖 onActivityResult。

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

    【讨论】:

    • 对不起朋友,我使用的是 Fragment 而不是 Activity。
    • 是的...但是在您使用添加片段的主要活动中使用此代码
    • 我不明白。因为我使用下面的代码。 FragmentTransaction fragmentTransaction = getSupportFragmentManager() .beginTransaction(); NewNoteFragment 片段 = 新的 NewNoteFragment(); fragmentTransaction.replace(R.id.flMain, 片段); fragmentTransaction.commit();
    猜你喜欢
    • 2014-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-13
    • 1970-01-01
    • 2019-10-07
    相关资源
    最近更新 更多