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>
相关推荐
小镇学者5 小时前
【PHP】导入excel 报错Trying to access array offset on value of type int
android·php·excel
一笑的小酒馆9 小时前
Android11 Launcher3去掉抽屉改为单层
android
louisgeek11 小时前
Git 根据不同目录设置不同账号
android
qq_3909347412 小时前
MySQL中的系统库(简介、performance_schema)
android·数据库·mysql
whysqwhw12 小时前
Kotlin Flow 实现响应式编程指南
android
二流小码农13 小时前
鸿蒙开发:一文了解桌面卡片
android·ios·harmonyos
每次的天空13 小时前
Android第十七次面试总结(Java数据结构)
android·java·面试
梁同学与Android13 小时前
Android --- Handler的用法,子线程中怎么切线程进行更新UI
android·handler·子线程更新ui·切换到主线程
Fastcv13 小时前
这TextView也太闪了,咋做的?
android
恋猫de小郭13 小时前
iOS 26 beta1 重新禁止 JIT 执行,Flutter 下的 iOS 真机 hot load 暂时无法使用
android·前端·flutter