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>
相关推荐
whysqwhw8 分钟前
OkHttp平台抽象机制分析
android
hsx6661 小时前
Android 内存泄漏避坑
android
whysqwhw1 小时前
OkHttp之okhttp-bom模块的分析
android
餐桌上的王子1 小时前
Android 构建可管理生命周期的应用(二)
android
幽你一默2 小时前
Android 版本差异速查表(开发者视角)
android
不萌2 小时前
android 项目中的屏幕适配方案
android
幽你一默2 小时前
Android开发三分钟读懂mvc,mvp,mvvm,mvi
android
小仙女喂得猪4 小时前
2025 源码应用: Retrofit之动态更换BaseUrl
android·android studio
AmazingMQ4 小时前
Android 13----在framworks层映射一个物理按键
android
小李飞飞砖5 小时前
Android 插件化实现原理详解
android