實現(xiàn)一個Android中更換頭像功能

實現(xiàn)一個Android中更換頭像功能

本文原創(chuàng),轉(zhuǎn)載請經(jīng)過本人準許

寫在前面:

更換頭像這個功能在用戶界面幾乎是100%出現(xiàn)的。通過拍攝照片或者調(diào)用圖庫中的圖片,并且進行剪裁,來進行頭像的設(shè)置。

功能相關(guān)截圖如下:

用戶界面,頭像未設(shè)置
點擊頭像,彈出Dialog
選擇照片,進行剪裁
頭像設(shè)置成功

下面我們直接看看完整代碼吧:


public class UserActivity extends BaseActivity implements OnClickListener {

    private ImageView iv_photo;
    private Bitmap head;// 頭像Bitmap
    private static String path = "/sdcard/myHead/";// sd路徑

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initListener();
    }

    private void initView() {
        setContentView(R.layout.activity_user);
        iv_photo = (ImageView) findViewById(R.id.iv_photo);
        Bitmap bt = BitmapFactory.decodeFile(path + "head.jpg");// 從SD卡中找頭像,轉(zhuǎn)換成Bitmap
        if (bt != null) {
            @SuppressWarnings("deprecation")
            Drawable drawable = new BitmapDrawable(bt);// 轉(zhuǎn)換成drawable
            iv_photo.setImageDrawable(drawable);
        } else {
            /**
             * 如果SD里面沒有則需要從服務(wù)器取頭像,取回來的頭像再保存在SD中
             * 
             */
        }
    }

    private void initListener() {
        iv_photo.setOnClickListener(this);
    }
    
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.iv_photo:// 更換頭像
            showTypeDialog();
            break;
        }
    }

    private void showTypeDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final AlertDialog dialog = builder.create();
        View view = View.inflate(this, 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 OnClickListener() {// 在相冊中選取
            @Override
            public 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 OnClickListener() {// 調(diào)用照相機
            @Override
            public 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();
    }

    @Override
    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) {
                    /**
                     * 上傳服務(wù)器代碼
                     */
                    setPicToView(head);// 保存在SD卡中
                    iv_photo.setImageBitmap(head);// 用ImageView顯示出來
                }
            }
            break;
        default:
            break;

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 調(diào)用系統(tǒng)的裁剪功能
     * 
     * @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", 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();// 創(chuàng)建文件夾
        String fileName = path + "head.jpg";// 圖片名字
        try {
            b = new FileOutputStream(fileName);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把數(shù)據(jù)寫入文件
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                // 關(guān)閉流
                b.flush();
                b.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

再添加以下權(quán)限

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
    <uses-permission android:name="android.permission.INTERNET" />

Dialog的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" >
    <TextView
        android:id="@+id/tv_select_gallery"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:padding="20dp"
        android:text="從圖庫中選取"
        android:textColor="#000"
        android:textSize="20sp" />

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:background="#000" />

    <TextView
        android:id="@+id/tv_select_camera"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:padding="20dp"
        android:text="拍攝照片"
        android:textColor="#000"
        android:textSize="20sp" />

</LinearLayout>

代碼的注釋還算全面,仔細閱讀一定能看懂,大家可以試試這個demo~這樣一個更換頭像的功能就實現(xiàn)了。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,872評論 25 709
  • ¥開啟¥ 【iAPP實現(xiàn)進入界面執(zhí)行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開一個線程,因...
    小菜c閱讀 7,311評論 0 17
  • 內(nèi)容抽屜菜單ListViewWebViewSwitchButton按鈕點贊按鈕進度條TabLayout圖標下拉刷新...
    皇小弟閱讀 47,144評論 22 665
  • 今天上午,媽媽接我放學的時候,我看見了我六樓的朋友, 因為下著雨,她的媽媽騎著電車,我就對她說:“你坐我家的車吧?...
    王輝霞閱讀 291評論 2 1
  • 異常的喜歡拍街道,那些開闊或狹窄的馬路總給我很多想象,車來人往,像是一個個故事正在發(fā)生,然后又消失?;蛟S有人悵惘,...
    半畝人閱讀 466評論 4 1

友情鏈接更多精彩內(nèi)容