首页 > 其他分享 >AndroidStudio - - - 点击头像更换头像_菜单选择_相机拍照与相册获取

AndroidStudio - - - 点击头像更换头像_菜单选择_相机拍照与相册获取

时间:2024-09-15 22:52:09浏览次数:3  
标签:相册 androidx fragment 头像 AndroidStudio new import android view

1. 逻辑代码

1.1 MainActivity 类


package com.example.myapplication;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

import android.os.Parcelable;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link BlankFragment4#newInstance} factory method to
 * create an instance of this fragment.
 */
public class BlankFragment4 extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private ImageView imageView;// 定义全局的 imageView
    private TextView textView; // 昵称

    public BlankFragment4() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment BlankFragment2.
     */
    // TODO: Rename and change types and number of parameters
    public static BlankFragment4 newInstance(String param1, String param2) {
        BlankFragment4 fragment = new BlankFragment4();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        // 普遍用view
        View view = inflater.inflate(R.layout.fragment_blank4, container, false);
        // 普遍用view
        // TODO 头像组件
        ImageView img = view.findViewById(R.id.imageView);
        img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("tag","点击换头像");
                // 弹出菜单框 选择从相机拍照 还是 选择图库
                // context : 传入activity对象
                // 使用方法 1.this在activity中 2.activity.this同1 3.在Fragment中使用getActivity()
                AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
                dialog.setItems(new String[]{"拍照", "相册"},
                        new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 点击后,具体处理,
                        Log.i("tag","which " + which);
                        Log.i("tag","dialog " + dialog);
                        // 判断 which 从而判断用户点击的是第几个
                        if (which == 0) {
                            // 调用系统相机权限 弹出是否同意授权
                            requestPermissions(new String[]{
                                    Manifest.permission.CAMERA,
                                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                            },10);// 动态申请权限
                        } else if (which == 1) {
                            // 调用系统相机 直接打开
                            Intent intent = new Intent();
                            // ACTION_GET_CONTENT = "android.intent.action.GET_CONTENT"
                            intent.setAction(Intent.ACTION_PICK); // 设置跳转到相册
                            intent.setType("image/*"); // 设置类型 选图片
                            startActivityForResult(intent,3);
                        }
                    }
                });
                dialog.show();
            }
        });
        // TODO 昵称行组件
        // 获取昵称
        textView = view.findViewById(R.id.save_nick_name);
        LinearLayout linearLayout = view.findViewById(R.id.nick_name);
        linearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("tag","点击换昵称"); // 调试
                Intent intent = new Intent(getActivity(), ChangeNickname.class);
                // 跳转后,当返回时能返回数据
                startActivityForResult(intent, 2);
            }
        });
        // 全局的 imageView 从 fragment_blank4 实例 view 获取
        imageView = view.findViewById(R.id.imageView);
        return view;
    }

    // 动态权限回调 requestCode:10 上面的requestCode
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // TODO 相机activity
        if (requestCode == 10) { // 系统相机申请权限返回10
            // 判断用户是否同意, PERMISSION_GRANTED = 0 : =>同意
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 调用相机activity
                Intent intent = new Intent();
                intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE); // 参数="android.media.action.IMAGE_CAPTURE"
                startActivityForResult(intent,1); // 相机获取的数据的返回值
            }
        }
        
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            // 相机activity返回
            // 获取相机返回的图片 bitmap
            assert data != null;
            Bundle bundle = data.getExtras();
            assert bundle != null; // 调试宏,只在debug模式下有效。如果不满足条件,就会出现断言
            Bitmap bitmap = bundle.getParcelable("data");
            //
            imageView.setImageBitmap(bitmap);
        } else if (requestCode == 3) {
            // 获取相册返回的图片 uri对象
            // 例子:uri = content://com.google.android.apps.photos.contentprovider/-1/1/content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F22/ORIGINAL/NONE/609859626
            Uri uri = data.getData();
            imageView.setImageURI(uri);
        }
    }
}

2. 布局代码

2.1 XML 文件

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
    tools:context=".BlankFragment2">

    <!-- TODO: Update blank fragment layout -->

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="600dp"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="110dp"
            android:orientation="horizontal">

            <TextView
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="match_parent"
                android:textSize="20dp"
                android:text="头像"
                android:gravity="left|center"
                android:scaleType="fitXY"
                android:padding="20dp"/>

            <ImageView
                android:id="@+id/imageView"
                android:layout_width="80dp"
                android:layout_height="80dp"
                android:layout_gravity="center"
                android:layout_margin="20dp"
                android:src="@drawable/avatar" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/nick_name"
            android:layout_width="match_parent"
            android:layout_height="110dp"
            android:orientation="horizontal">

            <TextView
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="match_parent"
                android:textSize="20dp"
                android:text="昵称"
                android:gravity="left|center"
                android:padding="20dp"
                tools:ignore="RtlHardcoded" />

            <TextView
                android:id="@+id/save_nick_name"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="match_parent"
                android:textSize="15dp"
                android:text="小明"
                android:gravity="right|center"
                android:padding="20dp"/>

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="110dp"
            android:orientation="horizontal">

            <TextView
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="match_parent"
                android:textSize="20dp"
                android:text="微信号"
                android:gravity="left|center"
                android:padding="20dp"/>

            <TextView
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:gravity="right|center"
                android:padding="20dp"
                android:text="xiaoming"
                android:textSize="15dp" />

        </LinearLayout>

    </LinearLayout>

</FrameLayout>

3.配置代码

3.1 build.gradle 文件

apply plugin: 'com.android.application'

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.2"

    defaultConfig {
        applicationId "com.example.myapplication"
        minSdkVersion 16
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}
// 指定当前项目的所有依赖关系:本地依赖、库依赖、远程依赖
dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"]) // 本地依赖
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'androidx.navigation:navigation-fragment:2.1.0'
    implementation 'androidx.navigation:navigation-ui:2.1.0'
    testImplementation 'junit:junit:4.12' // 测试用例库
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}

3.2 AndroidManifest.xml 文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapplication">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:networkSecurityConfig="@xml/network_config"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme.NoActionBar">
        <activity android:name=".MainActivity3">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".MainActivity2" />
        <activity android:name=".MainActivity" />
    </application>
    <!-- 配置相机权限 -->
    <uses-permission android:name="android.permission.CAMERA"/>
    <!-- 配置相机权限 -->
</manifest>

标签:相册,androidx,fragment,头像,AndroidStudio,new,import,android,view
From: https://blog.51cto.com/zicl/12025957

相关文章

  • 阿里云盘突发“灾难级 Bug”,创建相册之后可以随意观看他人照片
    多名网友在社交媒体上反映,阿里云盘出现了一起令人震惊的隐私安全事件。据用户反馈,在阿里云盘的相册功能中,只要创建一个新的文件夹,竟然能够自动加载并显示其他用户的照片,这些照片内容多样,包括自拍、风景照、家人旅游照片等,引发了广泛关注和讨论。据报道,9月14日晚,多位网友在......
  • 基于django+vue电子相册管理系统【开题报告+程序+论文】-计算机毕设
    本系统(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。系统程序文件列表开题报告内容研究背景随着数字技术的飞速发展,人们日常生活中拍摄的照片数量急剧增加,如何高效、有序地管理和存储这些珍贵的记忆成为了亟待解决的问题。传统的纸......
  • SpringMvc 完整上传文件流程(Ajax请求)头像,图片上传
    1、config包下的操作1.1、创建MyWebApplicationInit类如何创建第一个SpringMvc步骤以配置类的形式代替xml文件(点击链接查看)1.2、设置文件大小(自定义)1.3、创建SpringMvcConfig类并实现WebMvcConfigurer接口@EnableWebMvcpublicclassSpringMvcConfigimplementsWeb......
  • AI生成头像表情包,一次十分钟,就能实现月入过万的玩法,无脑操作
    今天给大家带来的项目是AI生成表情包和头像,这个项目对于我们做ip来说是真心不错,就比如我这个头像。为什么说每天只需要10分钟呢,那么我们继续往下看。"项目介绍这个项目的核心其实就是使用AI生成表情包或者说生成头像,我们再小红书上运营一个账号,通过发布图文吸引粉丝。......
  • 娱乐小平板(功能:相册、游戏、画图、刮刮乐)
    #include<sys/types.h>#include<sys/stat.h>#include<fcntl.h>#include<unistd.h>#include<stdio.h>#include<sys/mman.h>//mmap#include<linux/input.h>#include<string.h>#include<pthread.h>#in......
  • androidstudio报错devicemanager出错问题
    2024-09-0911:01:57,029[1446798]WARN-Emulator:Pixel8ProAPI35-Failedtoprocess.inifileC:\Users\钁f旦.android\avd<build>.iniforreading.如如何解决1.查日志C:\Users\董浩\AppData\Local\Google\AndroidStudio2024.1\log这个是默认位置我的错误是202......
  • 国庆节微信头像怎么制作?制作国庆国旗节日头像的4个方法
    国庆将至,不少朋友的微信头像都换成了渐变红旗头像,是不是觉得超酷呢?如果你也想拥有这样的头像,那就跟着这篇文章一起操作吧! 国庆节前夕,让我们先来了解一下如何制作渐变红旗头像。首先,我们需要找到一款能够实现这一功能的软件。这里推荐使用一键抠图工具,它不仅能够精准批量抠出人像......
  • uniapp 微信小程序获取头像,上传服务器
    html头像UI<buttonclass="user-avatarflex-center"open-type="chooseAvatar"@chooseavatar="onChooseAvatar"><imageclass="img":src="showAvatat()"mode="scaleToFill"/>......
  • Unity3d 截屏保存到相册,并且刷新相册
    要做一个截图的功能,并且玩家可以在相册中看到。 做的时候遇到了三个问题: 1、unity自带的截图API,Application.CaptureScreenshot在Android上不生效 2、图片保存的路径获取 3、保存的图片可以在手机的文件管理中找到,但是相册中没有。 解决......
  • AI变现之Midjourney头像定制
    前言Midjourney|头像定制1.项目介绍个性化头像在如今的社交媒体时代变得越来越重要。传统头像照片有时显得普通,而AI绘画头像则能为自己的社交账号增加独特性和吸引力。通过AI绘画工具制作头像,可以获得一个充满创意和个性的头像,让自己在社交平台上脱颖而出。2.项目......