繁体   English   中英

在Android的ImageView中显示图像

[英]Display image in imageview in android

我在ImageView布局上设置了onClickListener ,并尝试显示手机中的图像。 我到处都在寻找该过程,并且大多数都相似。 因此它应该可以工作,但是图像不会显示在imageview中。 也许我没有以正确的方式进行处理,因为所有事情都是零碎发生的。 在片段中,我用于显示图像的代码。 我需要克服的建议。

public class UserProfile extends Fragment {

    private ImageView profileImg;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_user_profile, container, false);
        profileImg = (ImageView) v.findViewById(R.id.imageView_profile);
        profileImg.setOnClickListener(chngImgHandler);
        return v;
    }

    OnClickListener chngImgHandler = new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Complete action using"), 1);
        }
    };

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1 && resultCode == getActivity().RESULT_OK) {
            // Bitmap photo = (Bitmap) data.getData().getPath();
            Uri selectedImageUri = data.getData();
            imagepath = getPath(selectedImageUri);
            Bitmap bitmap = BitmapFactory.decodeFile(imagepath);
            profileImg.setImageBitmap(bitmap);
        }

    }

    public String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        @SuppressWarnings("deprecation")
        Cursor cursor = getActivity().managedQuery(uri, projection, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

用户个人资料的布局

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:background="@color/profilepicBG"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imageView_profile"
        android:layout_width="120dp"
        android:layout_height="100dp"
        android:layout_gravity="center"
        android:layout_marginTop="25dp"
        android:src="@drawable/ic_launcher" />

    <Button
        android:id="@+id/btnChangePicture"
        android:layout_width="100dp"
        android:layout_height="40dp"
        android:layout_gravity="center"
        android:layout_marginTop="15dp"
        android:text="You?"
        android:textColor="#fff"
        android:textSize="12sp" />
</LinearLayout>

这是内部人士吗? 因为我在任何地方都看不到您对profileImg的声明。 尝试添加:

private ImageView profileImg;

..在全班最高水平。 或者,如果不是这种情况,请尝试添加:

intent.putExtra("return-data", true);

..到您的onClick方法声明。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM