android 调用图库中选择的图片
要求:
- 屏幕上显示一个按钮和图片视图控件。
- 点击“载入图片”按钮,将用户重定向到Android的图片库,在那里可以选择一个图片。
- 一旦图片被选中,图片将在主屏
工程名为ThePhotoFromSystem
-
2修改layout/main.xml布局文件:
步骤:
1 创建一个android工程,http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1">
3在MainActivity完成业务逻辑
package cn.xzmd.diaoyong.photo;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity {
private static int RESULT_LOAD_IMAGE = 10;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
//为按钮设置点击事件
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
//点击事件,而重定向到图片库
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//这里要传一个整形的常量RESULT_LOAD_IMAGE到startActivityForResult()方法。
startActivityForResult(intent, RESULT_LOAD_IMAGE);
}
});
}
//用户选择一张图片,onActivityResult()方法将会被调用,
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//我们需要判断requestCode是否是我们之前传给startActivityForResult()方法的RESULT_LOAD_IMAGE,并且返回的数据不能为空
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));
}
}
}
效果如下
更多相关文章
- Android开发环境(入门)
- AndroidStudio部署项目时出现错误:Instant Run requires 'Tools |
- android 图片溢出问题2...[geoway]
- Android中自定义控件
- 系出名门Android(5) - 控件(View)之TextView, Button, ImageButt
- 【转】详解android:scaleType属性
- 关于visibility的属性值visible,invisible,gone的区别
- Android菜鸟日记24-android小技巧
- android的selector,背景选择器