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>
相关推荐
胖虎15 小时前
Android 布局系列(五):GridLayout 网格布局的使用
android·网格布局·安卓布局·gridlayout
云泽野5 小时前
Pytest之parametrize参数化
android·python·pytest
野有蔓草W6 小时前
Android实现漂亮的波纹动画
android·java
万户猴7 小时前
【Flow进阶篇一】SharedFlow 入门:冷流 vs. 热流的区别与基础用法
android·kotlin
万户猴7 小时前
【Flow进阶篇二】SharedFlow 缓存机制深度解析
android·kotlin·android jetpack
李大圣的博客8 小时前
使用binlog2sql来恢复mysql误删除数据
android
奥顺8 小时前
PHP函数与类:面向对象编程实践指南
android·开发语言·mysql·开源·php
向上的车轮9 小时前
40岁开始学Java:Java中单例模式(Singleton Pattern),适用场景有哪些?
android·java·单例模式
人民的石头11 小时前
Android 系统 AMS(ActivityManagerService)
android
CYRUS_STUDIO14 小时前
unidbg 实现 JNI 与 Java 交互
android·安全·逆向