冲刺七

今天组做了什么:今天实现了从相册选取图片,获取权限

  

<LinearLayout 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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
tools:context=".TakeActivity">

<!-- 移动到下面的LinearLayout中 -->

<!-- 新增的LinearLayout用于水平排列ImageView和TextView -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"> <!-- 改为horizontal -->

<ImageView
android:id="@+id/back"
android:layout_width="46dp"
android:layout_height="48dp"
android:src="@drawable/back"
android:layout_marginEnd="5dp" /> <!-- 添加间距以分隔视图 -->

<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:textSize="25dp"
android:text="搜索结果 ">


</TextView>

</LinearLayout>

<!-- 原本的垂直LinearLayout保持不变 -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<ImageView
android:id="@+id/iv"
android:layout_width="435dp"
android:layout_height="220dp"
android:layout_gravity="center"
android:scaleType="centerCrop"
android:src="@drawable/ic_launcher_foreground" />

<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>

</LinearLayout>选择的显示页面;
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// 用户同样授权
openGallery();
} else {
// 用户拒绝授权
Toast.makeText(this, "需要授予存储权限", Toast.LENGTH_SHORT).show();
Log.d("HL", "需要授予存储权限!");
Intent intent = new Intent(this,homeFragment.class);
startActivity(intent);
}
}
}

/**
* 打开相册
*/用于回调,实现权限的申请;
if (requestCode == OPEN_GALLERY_REQUEST_CODE) { // 检测请求码
if (resultCode == Activity.RESULT_OK && data != null) {

InputStream inputStream = null;
try {
inputStream = getContentResolver().openInputStream(data.getData());
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
// TODO 把获取到的图片放到ImageView上
iv.setImageBitmap(bitmap);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); // 100表示压缩质量
byte[] byteArray = baos.toByteArray();
posted @ 2024-05-29 08:58  ZzHhyao  阅读(11)  评论(0)    收藏  举报