編輯:關於 Android 程式設計
哈囉,祝大家週末愉快!前陣子分享了几个專案裡經常出現的實用案例,反響還不錯,看來大家更在意技術能不能真正落到專案裡。所以這次我們就來把「更換頭像」這個功能從頭到尾做一遍。
不管是大型 App 還是小型專案,幾乎都繞不開頭像這件事。它是那種到處都能用上的基礎能力,值得花時間真正弄懂。
整個功能的骨架其實不複雜,主要涉及三塊:
1. startActivityForResult() 的用法與結果回傳機制;
2. 圖片檔案的讀寫與儲存;
3. PopupWindow 的彈出與互動。
如果這三塊你都已經熟悉,那這篇文章讀起來會非常輕鬆。
為了讓程式碼更乾淨,我沒有把所有邏輯塞進 Activity,而是單獨寫了一個 MPoPuWindow,負責彈窗本身的呈現以及「拍照 / 相簿 / 取消」三個選項的行為。先看程式碼:
public class MPoPuWindow extends PopupWindow implements OnClickListener {
public Context mContext;
private Type type;
public Activity mActivity;
private File file;
private Uri ImgUri;
private TextView mTakePhoto, mAlbumPhoto, mCancel;
public MPoPuWindow(Context context, Activity mActivity) {
initView(context);
this.mActivity = mActivity;
}
private void initView(Context mContext) {
this.mContext = mContext;
View v = LayoutInflater.from(mContext).inflate(R.layout.activity_popu, null);
setContentView(v);
mTakePhoto = (TextView) v.findViewById(R.id.photo_take);
mAlbumPhoto = (TextView) v.findViewById(R.id.photo_album);
mCancel = (TextView) v.findViewById(R.id.photo_cancel);
mTakePhoto.setOnClickListener(this);
mAlbumPhoto.setOnClickListener(this);
mCancel.setOnClickListener(this);
// 寬度鋪滿、高度佔滿整個螢幕
this.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
this.setHeight(ScreenUtils.getScreenHeight(mContext));
this.setTouchable(true);
this.setFocusable(true);
this.setOutsideTouchable(true);
this.update();
// 由下往上彈出的動畫
this.setAnimationStyle(R.style.popuwindow_from_bottom);
// 半透明遮罩背景
ColorDrawable dw = new ColorDrawable(0x50000000);
this.setBackgroundDrawable(dw);
}
public void showPopupWindow(View parent) {
if (!this.isShowing()) {
this.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
} else {
this.dismiss();
}
}
@Override
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.photo_take:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
file = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
ImgUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, ImgUri);
mActivity.startActivityForResult(intent, 1);
type = Type.CAMERA;
if (listener != null) {
listener.getType(type);
listener.getImgUri(ImgUri, file);
}
this.dismiss();
break;
case R.id.photo_album:
Intent intent2 = new Intent(Intent.ACTION_PICK);
intent2.setType("image/*");
mActivity.startActivityForResult(intent2, 2);
type = Type.PHONE;
if (listener != null) listener.getType(type);
this.dismiss();
break;
case R.id.photo_cancel:
this.dismiss();
break;
default:
break;
}
}
public void onPhoto(Uri uri, int outputX, int outputY) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", outputX);
intent.putExtra("outputY", outputY);
intent.putExtra("scale", true);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
intent.putExtra("return-data", true);
intent.putExtra("circleCrop", true);
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
intent.putExtra("noFaceDetection", true);
mActivity.startActivityForResult(intent, 3);
}
public interface onGetTypeClckListener {
void getType(Type type);
void getImgUri(Uri ImgUri, File file);
}
private onGetTypeClckListener listener;
public void setOnGetTypeClckListener(onGetTypeClckListener listener) {
this.listener = listener;
}
}
關鍵位置我都寫上了註解。這裡最值得留意的是:為了讓外部能拿到「使用者選了什麼、圖在哪」,我額外定義了一個回呼介面,對外暴露 getType() 與 getImgUri() 兩個方法,把照片來源類型與對應的 Uri、File 傳出去。
光有功能還不夠,順手把轉場做得舒服一些:
<style name="popuwindow_from_bottom">
<item name="android:windowEnterAnimation">@anim/popu_show_from_bottom</item>
<item name="android:windowExitAnimation">@anim/popu_hiden_from_top</item>
</style>
對應到 res/anim 下的兩個檔案:popu_show_from_bottom.xml 負責進場(由下往上滑入),popu_hiden_from_top.xml 負責退場(往下收回)。兩個都是最簡單的 <set> 加 <translate> 組合,重點是讓彈窗出現與消失的方向感一致。
public class MainActivity extends Activity {
private ImageView mIvThumb;
private File file;
private Uri ImgUri;
private Type type;
private MPoPuWindow puWindow;
public enum Type { PHONE, CAMERA }
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mIvThumb = (ImageView) findViewById(R.id.btn_change);
mIvThumb.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
puWindow = new MPoPuWindow(MainActivity.this, MainActivity.this);
puWindow.showPopupWindow(findViewById(R.id.set_act_parent));
puWindow.setOnGetTypeClckListener(new onGetTypeClckListener() {
@Override
public void getType(Type type) {
MainActivity.this.type = type;
}
@Override
public void getImgUri(Uri ImgUri, File file) {
MainActivity.this.ImgUri = ImgUri;
MainActivity.this.file = file;
}
});
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) { // 相機回來
if (ImgUri != null) puWindow.onPhoto(ImgUri, 300, 300);
} else if (requestCode == 2) { // 相簿回來
if (data != null) {
Uri uri = data.getData();
puWindow.onPhoto(uri, 300, 300);
}
} else if (requestCode == 3) { // 裁剪回來
if (type == Type.PHONE) {
if (data != null) {
Bundle extras = data.getExtras();
Bitmap bitmap = (Bitmap) extras.get("data");
if (bitmap != null) mIvThumb.setImageBitmap(bitmap);
}
} else if (type == Type.CAMERA) {
mIvThumb.setImageBitmap(BitmapFactory.decodeFile(file.getPath()));
}
}
}
}
這裡的重點全在 onActivityResult()。三個分支對應三種返回情境:從相機回來、從相簿回來、從裁剪介面回來,各自走不一樣的收尾處理。要注意的是裁剪結果的大小受限於 outputX/outputY,如果需要更清晰的頭像,實務上更常見的做法是走 FileProvider 搭配 EXTRA_OUTPUT 直接輸出到檔案,再自行做等比裁切,這樣可以避免 TransactionTooLargeException。
這兩個類幾乎每個專案都會用到,建議直接存起來當模板。
DensityUtils —— 單位轉換
public class DensityUtils {
private DensityUtils() { throw new UnsupportedOperationException("cannot be instantiated"); }
/** dp 轉 px */
public static int dp2px(Context context, float dpVal) {
return (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, dpVal,
context.getResources().getDisplayMetrics());
}
/** sp 轉 px */
public static int sp2px(Context context, float spVal) {
return (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_SP, spVal,
context.getResources().getDisplayMetrics());
}
/** px 轉 dp */
public static float px2dp(Context context, float pxVal) {
final float scale = context.getResources().getDisplayMetrics().density;
return pxVal / scale;
}
/** px 轉 sp */
public static float px2sp(Context context, float pxVal) {
return pxVal / context.getResources().getDisplayMetrics().scaledDensity;
}
}
ScreenUtils —— 螢幕相關資訊與截圖
public class ScreenUtils {
private ScreenUtils() { throw new UnsupportedOperationException("cannot be instantiated"); }
/** 螢幕寬度 */
public static int getScreenWidth(Context context) {
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
return outMetrics.widthPixels;
}
/** 螢幕高度 */
public static int getScreenHeight(Context context) {
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
return outMetrics.heightPixels;
}
/** 狀態列高度 */
public static int getStatusHeight(Context context) {
int statusHeight = -1;
try {
Class<?> clazz = Class.forName("com.android.internal.R$dimen");
Object object = clazz.newInstance();
int height = Integer.parseInt(
clazz.getField("status_bar_height").get(object).toString());
statusHeight = context.getResources().getDimensionPixelSize(height);
} catch (Exception e) {
e.printStackTrace();
}
return statusHeight;
}
/** 截圖,含狀態列 */
public static Bitmap snapShotWithStatusBar(Activity activity) {
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bmp = view.getDrawingCache();
int width = getScreenWidth(activity);
int height = getScreenHeight(activity);
Bitmap bp = Bitmap.createBitmap(bmp, 0, 0, width, height);
view.destroyDrawingCache();
return bp;
}
/** 截圖,不含狀態列 */
public static Bitmap snapShotWithoutStatusBar(Activity activity) {
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bmp = view.getDrawingCache();
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
int width = getScreenWidth(activity);
int height = getScreenHeight(activity);
Bitmap bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height - statusBarHeight);
view.destroyDrawingCache();
return bp;
}
}
寫到這裡,更換頭像的功能基本就完整了:彈窗選擇來源 → 系統相機或相簿 → 裁剪 → 回寫到 ImageView。整條鏈路都通過 startActivityForResult 串起來,邏輯集中、易於複用。
我的 Android 進階之旅:Java 檔案大小轉換工具類(B / KB / MB / GB / TB / PB)
Java 檔案大小轉換工具類(B、KB、MB、GB、TB、PB 之間的轉換) 做檔案管理或下載相關功能時,常會遇到需要把位元組數轉成人類看得懂的顯示格式,例如把 680
Android RecyclerView 新元件快速上手完整指南
RecyclerView 是 support-v7 套件中登場的一項全新元件,也是一款功能強大的捲動容器。相較於傳統的 ListView,它同樣具備 item 回收重複使
Android Develop 系列:構建系統解析
Android 構建系統是你用來構建、測試、運行和打包 App 的一整套工具。它既可以作為 Android Studio 的集成工具在菜單裡調用,也可以作為獨立命令執行。
基於 Distcc 搭建 Android 分散式編譯環境
網路上關於 Distcc 分散式編譯環境的文章不少,但大多數已經過時——照著做往往會卡在奇怪的編譯錯誤上。折騰一圈之後,我總算理出一條能真正跑通的完整步驟,而且還能啟用