Android-打开相册选中图片并显示

从之前的项目摘出来这段代码,去掉了裁剪功能

package com.example.one;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class InsertActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageView ivPicture;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_insert);

        initViews();
        bindClick();
    }

    private void bindClick() {
        ivPicture.setOnClickListener(this);
    }

    private void initViews() {
        ivPicture=findViewById(R.id.ivPicture);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ivPicture:
                Intent galleryIntent=new Intent(Intent.ACTION_GET_CONTENT);
                galleryIntent.addCategory(Intent.CATEGORY_OPENABLE);
                galleryIntent.setType("image/*");//图片
                startActivityForResult(galleryIntent,1);//跳转,传递打开相册请求码
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode!=RESULT_OK) {
            return;
        }else{
            switch (requestCode){
                case 1:
                    Uri uri=data.getData();
                    String[] images={MediaStore.Images.Media.DATA};//将获取到的
                    Cursor cursor=this.managedQuery(uri,images,null,null,null);
                    int index=cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    cursor.moveToFirst();
                    String img_uri=cursor.getString(index);
                    /*显示图片*/
                    showPicture(img_uri);
                    break;
            }
        }

    }

    /*显示图片*/
    private void showPicture(String img_uri) {
        ivPicture.setImageBitmap(BitmapFactory.decodeFile(img_uri));
    }
}

 

你可能感兴趣的:(Android知识)