Android开发 利用imageview显示选取的手机内存的图片

来源:互联网 发布:王者荣耀助手网络错误 编辑:程序博客网 时间:2024/06/13 05:18

activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent">    <Button            android:layout_width="fill_parent"           android:layout_height="wrap_content"           android:text="选择图片"          android:id="@+id/selectImage"          />    <ImageView            android:layout_width="wrap_content"           android:layout_height="wrap_content"           android:id="@+id/imageView"          />  </RelativeLayout>

MainActivity.java文件:

package com.example.imageview;import java.io.File;import java.io.FileNotFoundException;import android.app.Activity;import android.content.ContentResolver;import android.content.Intent;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.net.Uri;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.ImageView;public class MainActivity extends Activity {    private Button selectImage;    private ImageView imageView;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setTitle("ImageView");         setContentView(R.layout.activity_main);        selectImage = (Button) this.findViewById(R.id.selectImage);        imageView = (ImageView) this.findViewById(R.id.imageView);        selectImage.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View arg0) {                // TODO 自动生成的方法存根                Intent intent = new Intent();                //打开pictures画面Type设置为image                intent.setType("image/*");                //使用Intent.ACTION_GET_CONTENT 这个Action                intent.setAction(Intent.ACTION_GET_CONTENT);                //取得像片后返回本画面                startActivityForResult(intent, 1);            }        });    }    /**     * 定义方法onActivityResult来处理用户挑选的图片。通过requestCode和resultCode返回标识码,数据类型为Intent的data参数,     * 调用Intent对象的getData()方法可以获得具体内容。     */    protected void onActivityResult(int requestCode,int resultCode,Intent data){        if (resultCode==RESULT_OK){            Uri uri=data.getData();            ContentResolver cr=this.getContentResolver();            try{                Bitmap bitmap=BitmapFactory.decodeStream(cr.openInputStream(uri));                //将Bitmap设置到imageView                imageView.setImageBitmap(bitmap);            }catch(FileNotFoundException e)            {                e.printStackTrace();            }        }        super.onActivityResult(requestCode, resultCode, data);    }}

在AndroidManifest.xml文件中添加权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/><uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>

运行结果
这里写图片描述

0 0