package xatu.cn.androidtest_one; import android.content.ContentResolver; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import java.io.FileNotFoundException; /* 从手机相册中选择一幅图片并显示在屏幕上 */ public class MainActivity extends AppCompatActivity { private Button btn_choose; private ImageView img_show; private final int REQUEST_PICTURE_CHOOSE = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); event(); } private void init() { btn_choose = findViewById(R.id.btn_choose_picture); img_show = findViewById(R.id.imgview_src); } private void event() { btn_choose.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { 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){ Uri uri = data.getData(); Log.e("uri", uri.toString()); ContentResolver cr = this.getContentResolver(); try { Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri)); ImageView imageView = (ImageView) findViewById(R.id.imgview_src); /* 将Bitmap设定到ImageView */ imageView.setImageBitmap(bitmap); } catch (FileNotFoundException e) { e.printStackTrace(); } } super.onActivityResult(requestCode, resultCode, data); } } 页面布局代码: <?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:id="@+id/btn_choose_picture" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="选择图片" /> <ImageView android:id="@+id/imgview_src" android:layout_width="wrap_content" android:layout_height="0dp" android:layout_weight="1" /> </LinearLayout> </android.support.constraint.ConstraintLayout>
- 粉丝: 37
- 资源: 11
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助