更换头像后,只要不换虚拟机,头像一直都是最后一次更换的图片。重新运行或者卸载了重新安装,头像一直不变。
这里只有更换头像,所以简陋的弄一下,方便观察
先上效果图:运行环境eclipse Android4.4.2

卸载重新运行效果:

先在布局文件activity_main.xml中添加一个ImageView控件用来显示头像图片:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="fill_parent"android:layout_height="fill_parent"android:orientation="vertical"tools:context="${relativePackage}.${activityClass}" ><LinearLayout android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center_horizontal"android:layout_marginTop="80dp"android:orientation="vertical"><ImageView android:id="@+id/iv_head"android:layout_width="100dp"android:layout_height="100dp"android:contentDescription="@null"android:layout_gravity="center_horizontal"android:src="@drawable/default_icon"/></LinearLayout>
</LinearLayout>

注:android:src="@drawable/default_icon"这个是ImageView控件的默认背景图,如果不想要呢可以删除或者换成背景颜色,一点都不影响

然后再新建一个弹窗的布局文件activity_dialog_select.xml,效果如下:

具体代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="10dp"android:background="@drawable/dialog_bg_shape"android:orientation="vertical"><TextViewandroid:id="@+id/dialog_title"android:layout_width="match_parent"android:layout_height="37dp"android:gravity="center"android:text="请选择更换方式"android:textColor="#777777"android:textSize="14sp" /><Viewandroid:layout_width="match_parent"android:layout_height="0.2dp"android:background="#e5e5e5" /><TextViewandroid:id="@+id/photograph"android:layout_width="match_parent"android:layout_height="41dp"android:gravity="center"android:text="拍照"android:textColor="#444444"android:textSize="18sp" /><Viewandroid:layout_width="match_parent"android:layout_height="0.2dp"android:background="#e5e5e5" /><TextViewandroid:id="@+id/photo"android:layout_width="match_parent"android:layout_height="41dp"android:gravity="center"android:text="从相册中选择"android:textColor="#444444"android:textSize="18sp" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:layout_margin="10dp"android:background="@drawable/dialog_bg_shape"><TextViewandroid:id="@+id/cancel"android:layout_width="match_parent"android:layout_height="47dp"android:gravity="center"android:text="取消"android:textColor="#444444"android:textSize="18sp" /></LinearLayout>
</LinearLayout>

在这里,我们需要引入样式,使得这个弹窗的样子比较好看:dialog_bg_shape.xml一般放在drawable文件夹里面

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"android:shape="rectangle"><corners android:radius="15dp"/><solid android:color="#FFFFFF"/>
</shape>

之后就可以编写逻辑代码了:
先生成弹窗:这里使用的是dialog

 builder = new AlertDialog.Builder(this);//创建对话框inflater = getLayoutInflater();layout = inflater.inflate(R.layout.activity_dialog_select, null);//获取自定义布局builder.setView(layout);//设置对话框的布局dialog = builder.create();//生成最终的对话框dialog.setCanceledOnTouchOutside(true);//设置点击Dialog外部任意区域关闭dialog.show();//显示对话框

我用eclipse Android4.0运行发现弹窗后面有一个黑色的背景,怎么也去不掉,就像下面这样:

但是用Android studio的Android8.0运行又没有(项目6.0)

拍照用的是:

try {Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//开启相机应用程序获取并返回图片(capture:俘获)intent2.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"head.jpg")));//指明存储图片或视频的地址URIstartActivityForResult(intent2, 2);//采用ForResult打开} catch (Exception e) {Toast.makeText(MainActivity.this, "相机无法启动,请先开启相机权限", Toast.LENGTH_LONG).show();}

没有写权限哦,所以Android6.0及以上请自行添加权限

图片裁剪:

     Intent intent = new Intent("com.android.camera.action.CROP");//找到指定URI对应的资源图片intent.setDataAndType(uri, "image/*");intent.putExtra("crop", "true");// aspectX aspectY 是裁剪框宽高的比例intent.putExtra("aspectX", 1);intent.putExtra("aspectY", 1);// outputX outputY 是裁剪图片宽高intent.putExtra("outputX", 150);// 输出图片大小intent.putExtra("outputY", 150);intent.putExtra("return-data", true);//进入系统裁剪图片的界面startActivityForResult(intent, 3);

同样是高版本的不能用,我发现这就是一鸡肋。但为了应付老师,这几天也就弄出来这个,在网上疯狂的搜代码,靠,全部只适合高版本的,但那个老师叫我们弄的项目是4.0的,太气人了。

话不多说,别忘了在AndroidManifest.xml清单文件里面添加权限:

 <uses-permission android:name="android.permission.CAMERA" /><uses-feature android:name="android.hardware.camera"/><uses-feature android:name="android.hardware.camera.autofocus"/><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />

下面是完整的代码:这是两个布局文件共用一个逻辑代码文件

package china.ynyx.heyunhui;import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;public class MainActivity extends Activity implements OnClickListener{private ImageView iv_icon;private AlertDialog.Builder builder;private AlertDialog dialog;private LayoutInflater inflater;private View layout;private TextView takePhoto;private TextView choosePhoto;private TextView cancel;private static String path = "/sdcard/DemoHead/";//sd路径private Bitmap head;//头像Bitmap@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);intView();}private void intView() {// TODO Auto-generated method stubiv_icon = (ImageView) findViewById(R.id.iv_head);Bitmap bt = BitmapFactory.decodeFile(path + "head.jpg");//从Sd中找头像,转换成Bitmapif(bt!=null){@SuppressWarnings("deprecation")Drawable drawable = new BitmapDrawable(bt);//转换成drawableiv_icon.setImageDrawable(drawable);}else{/*** 如果SD里面没有则需要从服务器取头像,取回来的头像再保存在SD中* */}iv_icon.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {viewInit();}});}//初始化控件方法public void viewInit() {builder = new AlertDialog.Builder(this);//创建对话框inflater = getLayoutInflater();layout = inflater.inflate(R.layout.activity_dialog_select, null);//获取自定义布局builder.setView(layout);//设置对话框的布局dialog = builder.create();//生成最终的对话框dialog.setCanceledOnTouchOutside(true);//设置点击Dialog外部任意区域关闭dialog.show();//显示对话框takePhoto = (TextView) layout.findViewById(R.id.photograph);choosePhoto = (TextView) layout.findViewById(R.id.photo);cancel = (TextView) layout.findViewById(R.id.cancel);//设置监听takePhoto.setOnClickListener(this);choosePhoto.setOnClickListener(this);cancel.setOnClickListener(this);
}@Overridepublic void onClick(View view) {switch (view.getId()){case R.id.photograph://调用相机拍照//最好用try/catch包裹一下,防止因为用户未给应用程序开启相机权限,而使程序崩溃try {Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//开启相机应用程序获取并返回图片(capture:俘获)intent2.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"head.jpg")));//指明存储图片或视频的地址URIstartActivityForResult(intent2, 2);//采用ForResult打开} catch (Exception e) {Toast.makeText(MainActivity.this, "相机无法启动,请先开启相机权限", Toast.LENGTH_LONG).show();}dialog.dismiss();break;case R.id.photo://从相册里面取照片Intent intent1 = new Intent(Intent.ACTION_PICK, null);//返回被选中项的URIintent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");//得到所有图片的URIstartActivityForResult(intent1, 1);dialog.dismiss();break;case R.id.cancel:dialog.dismiss();//关闭对话框break;default:break;}}protected void onActivityResult(int requestCode, int resultCode, Intent data) {switch (requestCode) {//从相册里面取相片的返回结果case 1:if (resultCode == RESULT_OK) {cropPhoto(data.getData());//裁剪图片}break;//相机拍照后的返回结果case 2:if (resultCode == RESULT_OK) {File temp = new File(Environment.getExternalStorageDirectory()+ "/head.jpg");cropPhoto(Uri.fromFile(temp));//裁剪图片}break;//调用系统裁剪图片后case 3:if (data != null) {Bundle extras = data.getExtras();head = extras.getParcelable("data");if (head != null) {/*** 上传服务器代码*/setPicToView(head);//保存在SD卡中iv_icon.setImageBitmap(head);//用ImageView显示出来}}break;default:break;}super.onActivityResult(requestCode, resultCode, data);};/*** 调用系统的裁剪** @param uri*/public void cropPhoto(Uri uri) {Intent intent = new Intent("com.android.camera.action.CROP");//找到指定URI对应的资源图片intent.setDataAndType(uri, "image/*");intent.putExtra("crop", "true");// aspectX aspectY 是裁剪框宽高的比例intent.putExtra("aspectX", 1);intent.putExtra("aspectY", 1);// outputX outputY 是裁剪图片宽高intent.putExtra("outputX", 150);// 输出图片大小intent.putExtra("outputY", 150);intent.putExtra("return-data", true);//进入系统裁剪图片的界面startActivityForResult(intent, 3);}private void setPicToView(Bitmap mBitmap) {String sdStatus = Environment.getExternalStorageState();if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd卡是否可用return;}FileOutputStream b = null;File file = new File(path);file.mkdirs();// 创建以此File对象为名(path)的文件夹String fileName = path + "head.jpg";//图片名字try {b = new FileOutputStream(fileName);mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件(compress:压缩)} catch (FileNotFoundException e) {e.printStackTrace();} finally {try {//关闭流b.flush();b.close();} catch (IOException e) {e.printStackTrace();}}}
}

AndroidManifest.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.example.yuanjiaotouxiang"android:versionCode="1"android:versionName="1.0" ><uses-sdkandroid:minSdkVersion="8"android:targetSdkVersion="21" /><uses-permission android:name="android.permission.CAMERA" /><uses-feature android:name="android.hardware.camera"/><uses-feature android:name="android.hardware.camera.autofocus"/><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /><applicationandroid:allowBackup="true"android:icon="@drawable/ic_launcher"android:label="@string/app_name"android:theme="@android:style/Theme.Light.NoTitleBar"><activityandroid:name=".MainActivity"android:label="@string/app_name" ><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application></manifest>

demo地址:
   

Android之更换头像相关推荐

  1. [转]5分钟实现Android中更换头像功能

    5分钟实现Android中更换头像功能 写在前面: 更换头像这个功能在用户界面几乎是100%出现的.通过拍摄照片或者调用图库中的图片,并且进行剪裁,来进行头像的设置. 功能相关截图如下: 下面我们直接 ...

  2. Android实现换发型功能,实现一个Android中更换头像功能

    实现一个Android中更换头像功能 本文原创,转载请经过本人准许 写在前面: 更换头像这个功能在用户界面几乎是100%出现的.通过拍摄照片或者调用图库中的图片,并且进行剪裁,来进行头像的设置. 功能 ...

  3. 5分钟实现Android中更换头像功能

    写在前面: 更换头像这个功能在用户界面几乎是100%出现的.通过拍摄照片或者调用图库中的图片,并且进行剪裁,来进行头像的设置. 功能相关截图如下: 下面我们直接看看完整代码吧: 1 2 3 4 5 6 ...

  4. 【Android】更换头像的实现

    现在不管什么APP都有个头像,如果你看见没有头像的APP就会感觉非常奇怪,以前头像都是方的,后来就变成圆的,我估计在过个几年就得来个五角星形状的头像,下面我把更换头像的代码写来: <Relati ...

  5. Android 项目更换头像(拍照和选择相册)

    之前开发项目的时候一直没有做更换头像这一块,因为开发的东西很少有需要用户进行登录的,最近比较闲,记录一下修改头像这一块, 就不说需求了 看图 场景很简单,也符合更换头像的需求 描述:点击头像 ,弹出菜 ...

  6. Android中更换头像功能的实现

    点击头像实现更换头像,可以从相册里进行更换,也可以拍摄照片更换 运行效果图 点击从相册中选择,选择图片 点击从相册中选择 Activity中的代码,因为这是在我的项目中做的所以有些代码是没有必要的,在 ...

  7. Android实现更换头像功能(适配Android7.0版本)

    只要涉及到用户的功能,基本都会使用到用户头像功能.那么切换用户头像,就是一个必做的功能.切换头像的图片源,一般有两个:一个是拍照然后裁剪图片,另一种是从图库中选择图片,然后裁剪图片.所以这里就来实现这 ...

  8. android studio更换头像,明版明日大富翁 -官方网站

    开发者 javascript属于弱类型,值包含:数字,字符串和布尔值,c++与java属于强类型;int a="a",string a="a" 报错;var a ...

  9. Android - 更换头像及图片裁剪(适配Android7.0)

    我的CSDN: ListerCi 我的简书: 东方未曦 一.概述 相信大家都用过 Android 应用中更换头像的功能,在这个功能中,用户可以拍照或者选择相册图片,然后裁剪出头像所需要的图案. 那么你 ...

最新文章

  1. C++ 关于方法传值
  2. mysql执行语句_实时查看MySQL执行的语句
  3. eclipse注释模板_Intellij IDEA设置默认文档注释
  4. 避免一个用户多次登录修改版
  5. 人事面试的那些问题及背后的考察点
  6. 三星Galaxy S20 FE 5G正式在国内发布 售价4999元起
  7. python函数可以递归调用吗_递归调用函数
  8. kalilinux装到u盘上的弊端_你有一个 U 盘制作多系统安装盘的需求吗,YUMI 帮你秒实现!...
  9. 【2019南昌邀请赛网络赛 J】Distance on the tree【边权树剖+主席树】
  10. SMTP 550错误
  11. filp_open/filp_close/vfs_read/vfs_write
  12. MEMS传感器领域关于薄膜性能的中国国家标准,“带状薄膜抗拉性能的试验方法”由北京智芯传感等单位发布并实施
  13. html 输入年份,判断是否是闰年
  14. vue+海康威视视频插件坑点记录
  15. Maxent影响因子响应曲线重绘
  16. Javascript 在循环中使用Promise对象
  17. Qt学习之信号与槽函数断开:disconnect
  18. kafka巨坑 启动失败
  19. liunx挖矿程序排查思路
  20. 01_李宏毅机器学习

热门文章

  1. 拯救者y7000p进入BIOS
  2. OpenCV实现爱江山更爱美人时装周刷票
  3. 李刚疯狂java抄袭,推荐:疯狂java讲义--李刚著作(3)
  4. matlab打开相机
  5. boll指标(布林带)计算公式
  6. 量化交易 聚宽 布林带策略
  7. java学习p163
  8. C4D学习笔记2-动画-时间线及时间函数
  9. 苹果怎么换行打字_通过这 684 关小游戏,你的打字速度可以赢过专业录入员
  10. 【uni-app】App实现二维码分享图合成(支持单张或多张)