温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Android开发中怎么实现一个从图库中选取图片的功能

发布时间:2020-11-20 16:50:55 来源:亿速云 阅读:234 作者:Leah 栏目:移动开发

Android开发中怎么实现一个从图库中选取图片的功能?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

android 从图库中选取图片

 在android中,如何从图库gallary中挑选图片呢,其实很简单,步骤如下

1) 设计一个imageview,用来显示图库选出来的图片 

<&#63;xml version="1.0" encoding="utf-8"&#63;> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  android:orientation="vertical" 
  android:layout_width="fill_parent" 
  android:layout_height="fill_parent" 
  > 
  <ImageView 
      android:id="@+id/imgView" 
      android:layout_width="fill_parent" 
      android:layout_weight="1" android:layout_height="wrap_content"></ImageView> 
  <Button  
      android:layout_height="wrap_content"  
      android:text="Load Picture"  
      android:layout_width="wrap_content"  
      android:id="@+id/buttonLoadPicture"  
      android:layout_weight="0"  
      android:layout_gravity="center"></Button> 
</LinearLayout> 



2) 学习如何在按键中调出gallary,其实也就是intent了,如下 

  Intent i = new Intent(Intent.ACTION_PICK, android.
provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
 startActivityForResult(i, RESULT_LOAD_IMAGE); 

3) 然后在onActivityResult中对调出图库后,选定好的图片,我们要重新显示在页面的imageview中,因此代码如下: 

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

  其中就是Uri selectedImage = data.getData();获得了图库中的图片所有数据了。

看完上述内容,你们掌握Android开发中怎么实现一个从图库中选取图片的功能的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI