点击头像实现更换头像,可以从相册里进行更换,也可以拍摄照片更换
运行效果图
点击从相册中选择,选择图片
点击从相册中选择
Activity中的代码,因为这是在我的项目中做的所以有些代码是没有必要的,在代码中写了注释,所以只需要从注释点击头像更换头像处看就好,
注意别忘了声明ImageButton按钮,Bitmap存放头像,path存放sd路径。
package com.bzu.fshiner.parttimejob.activity;import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
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.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;import com.bzu.fshiner.parttimejob.R;import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;import static android.app.Activity.RESULT_OK;/*** Created by Administrator on 2017/5/17.*/public class PersonalFragment extends Fragment {private LinearLayout LL01,LL02,LL03;private Context mContext;private ImageButton touxiang;private Bitmap head;// 头像Bitmapprivate static String path = "/sdcard/myHead/";// sd路径public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){return inflater.inflate(R.layout.personal_fragment,container,false);}@Overridepublic void onCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState);this.mContext = getActivity();}@Overridepublic void onActivityCreated(Bundle savedInstanceState) {super.onActivityCreated(savedInstanceState);initView();//查看个人信息LL01.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {Intent intent=new Intent(getActivity(),MorePersonActivity.class);startActivity(intent);}});//查看我的收藏LL02.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {Intent intent=new Intent(getActivity(),CollectionActivity.class);startActivity(intent);}});//查看我发布的所有兼职LL03.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {Intent intent=new Intent(getActivity(),MySendActivity.class);startActivity(intent);}});/*点击头像进行更换头像*/touxiang.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.touxiang:// 更换头像showTypeDialog();break;}}});}private void initView() {LL01=(LinearLayout)getActivity().findViewById(R.id.LL01);LL02=(LinearLayout)getActivity().findViewById(R.id.LL02);LL03=(LinearLayout)getActivity().findViewById(R.id.LL03);touxiang = (ImageButton)getActivity().findViewById(R.id.touxiang);Bitmap bt = BitmapFactory.decodeFile(path + "head.jpg");// 从SD卡中找头像,转换成Bitmapif (bt != null) {@SuppressWarnings("deprecation")Drawable drawable = new BitmapDrawable(bt);// 转换成drawabletouxiang.setImageDrawable(drawable);} else {/*** 如果SD里面没有则需要从服务器取头像,取回来的头像再保存在SD中**/}}private void showTypeDialog() {//显示对话框AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());final AlertDialog dialog = builder.create();View view = View.inflate(getActivity(), R.layout.dialog_select_photo, null);TextView tv_select_gallery = (TextView) view.findViewById(R.id.tv_select_gallery);TextView tv_select_camera = (TextView) view.findViewById(R.id.tv_select_camera);tv_select_gallery.setOnClickListener(new View.OnClickListener() {// 在相册中选取@Overridepublic void onClick(View v) {Intent intent1 = new Intent(Intent.ACTION_PICK, null);//打开文件intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");startActivityForResult(intent1, 1);dialog.dismiss();}});tv_select_camera.setOnClickListener(new View.OnClickListener() {// 调用照相机@Overridepublic void onClick(View v) {Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);intent2.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "head.jpg")));startActivityForResult(intent2, 2);// 采用ForResult打开dialog.dismiss();}});dialog.setView(view);dialog.show();}@Overridepublic 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卡中touxiang.setImageBitmap(head);// 用ImageButton显示出来}}break;default:break;}super.onActivityResult(requestCode, resultCode, data);}/*** 调用系统的裁剪功能** @param uri*/public void cropPhoto(Uri uri) {Intent intent = new Intent("com.android.camera.action.CROP");intent.setDataAndType(uri, "image/*");intent.putExtra("crop", "true");// aspectX aspectY 是宽高的比例intent.putExtra("aspectX", 1);intent.putExtra("aspectY", 1);// outputX outputY 是裁剪图片宽高intent.putExtra("outputX", 250);intent.putExtra("outputY", 250);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();// 创建文件夹String fileName = path + "head.jpg";// 图片名字try {b = new FileOutputStream(fileName);mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件} catch (FileNotFoundException e) {e.printStackTrace();} finally {try {// 关闭流b.flush();b.close();} catch (IOException e) {e.printStackTrace();}}}
}
在主布局文件中只需要写一个ImageButton按钮就好
<ImageButtonandroid:id="@+id/touxiang"android:layout_width="wrap_content"android:layout_height="wrap_content"android:padding="0dp"android:background="@drawable/person_default"android:layout_centerHorizontal="true"/>
另外还需要写一个布局文件,取名为dialog_select_photo.xml,这个布局是点击图片按钮时弹出的选择框。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:paddingLeft="60dp"android:paddingRight="60dp"><TextViewandroid:id="@+id/tv_select_gallery"android:layout_width="match_parent"android:layout_height="wrap_content"android:paddingTop="20dp"android:padding="20dp"android:gravity="center"android:text="从相册中选取" /><TextViewandroid:layout_below="@id/tv_select_gallery"android:id="@+id/tv_select_camera"android:layout_width="match_parent"android:layout_height="wrap_content"android:paddingBottom="20dp"android:gravity="center"android:text="拍摄照片" />
</RelativeLayout>