android开发,从本地选择图片,并显示出来

本文介绍了一个简单的Android应用,用于从设备中选择图片并显示在ImageView中。通过使用Intent和onActivityResult方法,实现了图片的选择与预览功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

xml布局activity_main:

<LinearLayout 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"
    android:orientation="vertical" >


    <Button
        android:id="@+id/picture"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="选择图片" />

    <ImageView
        android:id="@+id/src"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />
</LinearLayout>


MainActivity.java:


public class MainActivity extends Activity {

private final int REQUEST_PICTURE_CHOOSE=1;


Button btn;
ImageView img;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);

init();
event();
}


private void init() {
// TODO Auto-generated method stub
btn = (Button) findViewById(R.id.picture);
img = (ImageView) findViewById(R.id.src);
}

private void event() {
// TODO Auto-generated method stub
btn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(intent, REQUEST_PICTURE_CHOOSE);
}
});
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}


String fileSrc = null;
if (requestCode == Constants.REQUEST_PICTURE_CHOOSE) {
if ("file".equals(data.getData().getScheme())) {
// 有些低版本机型返回的Uri模式为file
fileSrc = data.getData().getPath();
} else {
// Uri模型为content
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(data.getData(),
proj, null, null, null);
cursor.moveToFirst();
int idx = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
fileSrc = cursor.getString(idx);
cursor.close();
}

//以下bitmap最好先进行缩放处理,这里就不处理了
Bitmap bitmap= BitmapFactory.decodeFile(fileSrc);
img.setImageBitmap(bitmap);
}
}


}


添加权限

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

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值