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>
相关推荐
alexhilton2 小时前
面向开发者的系统设计:像建筑师一样思考
android·kotlin·android jetpack
CYRUS_STUDIO11 小时前
用 Frida 控制 Android 线程:kill 命令、挂起与恢复全解析
android·linux·逆向
CYRUS_STUDIO11 小时前
Frida 实战:Android JNI 数组 (jobjectArray) 操作全流程解析
android·逆向
用户0915 小时前
Gradle Cache Entries 深度探索
android·java·kotlin
循环不息优化不止15 小时前
安卓 View 绘制机制深度解析
android
叽哥15 小时前
Kotlin学习第 9 课:Kotlin 实战应用:从案例到项目
android·java·kotlin
雨白1 天前
Java 线程通信基础:interrupt、wait 和 notifyAll 详解
android·java
诺诺Okami1 天前
Android Framework-Launcher-UI和组件
android
潘潘潘1 天前
Android线程间通信机制Handler介绍
android
潘潘潘1 天前
Android动态链接库So的加载
android