android跳转到相册选择图片

点击图片a,跳转到相册。选择一张图片b,图片a切换成图片b。

java 复制代码
package com.example.myapplication5;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

public class PicActivity3 extends AppCompatActivity implements View.OnClickListener {

    private static final int REQUEST_SELECT_MEDIA = 1;
    private ImageView img_add;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pic3);
        //添加图片按钮,点击跳转系统相册(使用intent)
        img_add = findViewById(R.id.img_add);
        img_add.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.img_add:
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("image/*"); // 选择图片
                // intent.setType("video/*"); // 选择视频
                startActivityForResult(intent, REQUEST_SELECT_MEDIA);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        Toast.makeText(PicActivity3.this,"选择图片",Toast.LENGTH_LONG).show();
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_SELECT_MEDIA && resultCode == RESULT_OK && data != null) {
            Uri selectedMediaUri = data.getData();

            // 处理选中的媒体文件
            img_add.setImageURI(selectedMediaUri);
        }
    }
}
xml 复制代码
<?xml version="1.0" encoding="utf-8"?>
<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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <ImageView
        android:id="@+id/img_add"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:src="@drawable/railway"
        />
</LinearLayout>
相关推荐
AI2中文网31 分钟前
App Inventor 对接 OneNet:手机收数据
android·鸿蒙·app inventor
好的佩奇36 分钟前
Dart 之文件读写
android·flutter·dart
砚底藏山河3 小时前
量化行情横截面中性化闭式与回归实现
android·java·python·金融·kotlin
明君6893 小时前
APK 签名绕过方案(Android 10~17)
android
芝麻别开门3 小时前
Android libmpv 源码下载与编译
android·mpv·libmpv
FLJwu3 小时前
运动相机代工模具风控③:试模样品、结构公差、装配干涉,提前规避大货装配不良
android·开发语言·数码相机·运动相机·oem 量产
应用市场4 小时前
安卓底层拆解(四)· 属性要成套:abilist 与 zygote 的连锁反应
android·zygote
齊家治國平天下5 小时前
Android Automotive(AAOS)系统入门:从五层架构到车载机制
android·架构·车载系统·aaos·智能座舱
我命由我123455 小时前
Android Gradle - Android Gradle 配置
android·java·linux·java-ee·kotlin·android studio·android-studio
SEO_juper8 小时前
PHP 关键词覆盖率检测工具:检查正文有没有覆盖该讲的词
android·开发语言·php