在之前的 Android 開發過程中,總結了許多的工具類,像類似的工具類其實有很多,這裡羅列出一些自己常用到的。其中有些是別人寫的,有些是自己總結的,抱歉,有些我實在找不到誰才是原創,下面這些工具類當中,有單位換算 (DensityUtils),螢幕寬高獲取(ScreenUtils),新式吐司互動類(SnackbarUtil),SharedPreferences 持久化常用方法的封裝(SPUtils),狀態列的設定(StatusBarUtil),日誌工具類(LogUtils),Toast 封裝(ToastUtils),這裡面的大多數自己都用過,誰用誰知道!
DensityUtils.java
public class DensityUtils {
//利用 Android 自帶 API
public static int dp2px(Context context, float dpVal){
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,dpVal, context.getResources().getDisplayMetrics());
}
public float dp2px(float dp) {
final float scale = getResources().getDisplayMetrics().density;
return dp * scale + 0.5f;
}
//利用 Android 自帶 API
public static int sp2px(Context context, float spVal){
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spVal, context.getResources().getDisplayMetrics());
}
public float sp2px(float sp) {
final float scale = getResources().getDisplayMetrics().scaledDensity;
return sp * scale;
}
//利用 Android 自帶 API px converteTo dp
public static float px2dp(Context context, float pxVal) {
final float scale = context.getResources().getDisplayMetrics().density;
return (pxVal / scale);
}
//利用 Android 自帶 API px converteTo sp
public static float px2sp(Context context, float pxVal) {
return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);
}
}
複製程式碼
專案中經常要用到 單位轉換,這個可以說是必備的
SPUtils.java
public class SPUtils {
public static final String PREF_NMAE = "config";
public static boolean getBoolan(Context context, String key, boolean defaultVal) {
SharedPreferences sp = context.getSharedPreferences(PREF_NMAE, Context.MODE_PRIVATE);
return sp.getBoolean(key, defaultVal);
}
public static void setBoolean(Context context, String key, boolean defaultVal) {
SharedPreferences sp = context.getSharedPreferences(PREF_NMAE, Context.MODE_PRIVATE);
sp.edit().putBoolean(key, defaultVal).commit();
}
public static String getString(Context context, String key, String defaultVal) {
SharedPreferences sp = context.getSharedPreferences(PREF_NMAE, Context.MODE_PRIVATE);
return sp.getString(key, defaultVal);
}
public static void setString(Context context, String key, String defaultVal) {
SharedPreferences sp = context.getSharedPreferences(PREF_NMAE, Context.MODE_PRIVATE);
sp.edit().putString(key, defaultVal).commit();
}
}
複製程式碼
ToastUtils.java
public class ToastUtils {
public static Toast mToast;
//單例的吐司
public static void singleTanceToast(Context context,String msg){
if (mToast == null) {
mToast = Toast.makeText(context, "", Toast.LENGTH_SHORT);
}
mToast.setText(msg);
mToast.show();
}
//短顯示toast
public static void shortShowToast(Context context,String message){
if (mToast == null){
mToast = Toast.makeText(context,message,Toast.LENGTH_SHORT);
}
mToast.show();
}
//長顯示toast
public static void longShowToast(Context context, String message) {
if (mToast == null) {
mToast = Toast.makeText(context, message, Toast.LENGTH_LONG);
}
mToast.show();
}
//自定義時長顯示toast
public static void customShowToast(Context context,String message,int duration){
if (mToast == null){
mToast = Toast.makeText(context,message,Toast.LENGTH_LONG);
}
mToast.setDuration(duration);
mToast.show();
}
/*
* 帶圖片的吐司
* backgroud 圖片id
* msg 顯示的字元
* mContext 上下文
*/
public static void showToastWithImage(Context mContext, int background, String msg) {
if (mToast == null) {
//mToast = Toast.makeText(mContext, "", Toast.LENGTH_SHORT);
mToast = new Toast(mContext);
}
LinearLayout mLinearLayout = new LinearLayout(mContext);
TextView mTextView = new TextView(mContext);
mTextView.setText(msg);
mTextView.setGravity(Gravity.CENTER_VERTICAL);// 設定文字居中
mTextView.setTextSize(16);
mTextView.setTextColor(Color.WHITE);// 字型大小和顏色
mTextView.setCompoundDrawablesWithIntrinsicBounds(background, 0, 0, 0);
mLinearLayout.setBackgroundResource(android.R.drawable.toast_frame);//Android自帶的背景色
mLinearLayout.addView(mTextView);
mToast.setView(mLinearLayout);
mToast.setGravity(Gravity.CENTER, 0, 0);
mToast.show();
}
}
複製程式碼
LogUtils.java
public class LogUtils {
public static final int VERBOSE = 1;
public static final int DEBUG = 2;
public static final int INFO = 3;
public static final int WARN = 4;
public static final int ERROR = 5;
public static final int NOTHING = 6;
public static final int LEVEL = VERBOSE;
public static void v(String tag, String msg) {
if (LEVEL <= VERBOSE) {
Log.v(tag, msg);
}
}
public static void d(String tag, String msg) {
if (LEVEL <= DEBUG) {
Log.d(tag, msg);
}
}
public static void i(String tag, String msg) {
if (LEVEL <= INFO) {
Log.i(tag, msg);
}
}
public static void w(String tag, String msg) {
if (LEVEL <= WARN) {
Log.w(tag, msg);
}
}
public static void e(String tag, String msg) {
if (LEVEL <= ERROR) {
Log.e(tag, msg);
}
}
}
複製程式碼
這個不錯,記得在郭神的書裡面有介紹
StatusBarUtil.java
public class StatusBarUtil {
/**
* 修改狀態列為全透明
* @param activity
*/
@TargetApi(19)
public static void transparencyBar(Activity activity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = activity.getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
| WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
window.setNavigationBarColor(Color.TRANSPARENT);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window window = activity.getWindow();
window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
}
/**
* 修改狀態列顏色,支援4.4以上版本
* @param activity
* @param colorId
*/
public static void setStatusBarColor(Activity activity, int colorId) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = activity.getWindow();
// window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(activity.getResources().getColor(colorId));
}
}
/**
* 設定狀態列黑色字型圖示,
* 適配4.4以上版本MIUIV、Flyme和6.0以上版本其他Android
*
* @param activity
* @return 1:MIUUI 2:Flyme 3:android6.0
*/
public static int StatusBarLightMode(Activity activity) {
int result = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
if (MIUISetStatusBarLightMode(activity.getWindow(), true)) {
result = 1;
} else if (FlymeSetStatusBarLightMode(activity.getWindow(), true)) {
result = 2;
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
result = 3;
}
}
return result;
}
/**
* 已知系統型別時,設定狀態列黑色字型圖示。
* 適配4.4以上版本MIUIV、Flyme和6.0以上版本其他Android
* @param activity
* @param type 1:MIUUI 2:Flyme 3:android6.0
*/
public static void StatusBarLightMode(Activity activity, int type) {
if (type == 1) {
MIUISetStatusBarLightMode(activity.getWindow(), true);
} else if (type == 2) {
FlymeSetStatusBarLightMode(activity.getWindow(), true);
} else if (type == 3) {
activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
}
}
/**
* 清除MIUI或flyme或6.0以上版本狀態列黑色字型
*/
public static void StatusBarDarkMode(Activity activity, int type) {
if (type == 1) {
MIUISetStatusBarLightMode(activity.getWindow(), false);
} else if (type == 2) {
FlymeSetStatusBarLightMode(activity.getWindow(), false);
} else if (type == 3) {
activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
}
}
/**
* 設定狀態列圖示為深色和魅族特定的文字風格
* 可以用來判斷是否為Flyme使用者
* @param window 需要設定的視窗
* @param dark 是否把狀態列字型及圖示顏色設定為深色
* @return boolean 成功執行返回true
*/
public static boolean FlymeSetStatusBarLightMode(Window window, boolean dark) {
boolean result = false;
if (window != null) {
try {
WindowManager.LayoutParams lp = window.getAttributes();
Field darkFlag = WindowManager.LayoutParams.class.getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
Field meizuFlags = WindowManager.LayoutParams.class.getDeclaredField("meizuFlags");
darkFlag.setAccessible(true);
meizuFlags.setAccessible(true);
int bit = darkFlag.getInt(null);
int value = meizuFlags.getInt(lp);
if (dark) {
value |= bit;
} else {
value &= ~bit;
}
meizuFlags.setInt(lp, value);
window.setAttributes(lp);
result = true;
} catch (Exception e) {
e.printStack();
}
}
return result;
}
/**
* 設定狀態列字型圖示為深色,需要MIUIV6以上
* @param window 需要設定的視窗
* @param dark 是否把狀態列字型及圖示顏色設定為深色
* @return boolean 成功執行返回true
*/
public static boolean MIUISetStatusBarLightMode(Window window, boolean dark) {
boolean result = false;
if (window != null) {
Class clazz = window.getClass();
try {
int darkModeFlag = 0;
Class layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
darkModeFlag = field.getInt(layoutParams);
Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
if (dark) {
extraFlagField.invoke(window, darkModeFlag, darkModeFlag);//狀態列透明且黑色字型
} else {
extraFlagField.invoke(window, 0, darkModeFlag);//清除黑色字型
}
result = true;
} catch (Exception e) {
}
}
return result;
}
}
複製程式碼
SnackbarUtil.java
public class SnackbarUtil {
public static final int Info = 1;
public static final int Confirm = 2;
public static final int Warning = 3;
public static final int Alert = 4;
public static int red = 0xfff44336;
public static int green = 0xff4caf50;
public static int blue = 0xff2195f3;
public static int orange = 0xffffc107;
/**
* 短顯示Snackbar,自定義顏色
* @param view
* @param message
* @param messageColor
* @param backgroundColor
* @return
*/
public static Snackbar ShortSnackbar(View view, String message, int messageColor, int backgroundColor){
Snackbar snackbar = Snackbar.make(view,message, Snackbar.LENGTH_SHORT);
setSnackbarColor(snackbar,messageColor,backgroundColor);
return snackbar;
}
/**
* 長顯示Snackbar,自定義顏色
* @param view
* @param message
* @param messageColor
* @param backgroundColor
* @return
*/
public static Snackbar LongSnackbar(View view, String message, int messageColor, int backgroundColor){
Snackbar snackbar = Snackbar.make(view,message, Snackbar.LENGTH_LONG);
setSnackbarColor(snackbar,messageColor,backgroundColor);
return snackbar;
}
/**
* 自定義Snackbar顯示時長,自定義顏色
* @param view
* @param message
* @param messageColor
* @param backgroundColor
* @return
*/
public static Snackbar IndefiniteSnackbar(View view, String message, int duration, int messageColor, int backgroundColor){
Snackbar snackbar = Snackbar.make(view,message, Snackbar.LENGTH_INDEFINITE).setDuration(duration);
setSnackbarColor(snackbar,messageColor,backgroundColor);
return snackbar;
}
/**
* 短顯示Snackbar,可選預設型別
* @param view
* @param message
* @param type
* @return
*/
public static Snackbar ShortSnackbar(View view, String message, int type){
Snackbar snackbar = Snackbar.make(view,message, Snackbar.LENGTH_SHORT);
switchType(snackbar,type);
return snackbar;
}
/**
* 長顯示Snackbar,可選預設型別
* @param view
* @param message
* @param type
* @return
*/
public static Snackbar LongSnackbar(View view, String message, int type){
Snackbar snackbar = Snackbar.make(view,message, Snackbar.LENGTH_LONG);
switchType(snackbar,type);
return snackbar;
}
/**
* 自定義時常顯示Snackbar,可選預設型別
* @param view
* @param message
* @param type
* @return
*/
public static Snackbar IndefiniteSnackbar(View view, String message, int duration, int type){
Snackbar snackbar = Snackbar.make(view,message, Snackbar.LENGTH_INDEFINITE).setDuration(duration);
switchType(snackbar,type);
return snackbar;
}
//選擇預設型別
private static void switchType(Snackbar snackbar, int type){
switch (type){
case Info:
setSnackbarColor(snackbar,blue);
break;
case Confirm:
setSnackbarColor(snackbar,green);
break;
case Warning:
setSnackbarColor(snackbar,orange);
break;
case Alert:
setSnackbarColor(snackbar, Color.YELLOW,red);
break;
}
}
/**
* 設定Snackbar背景顏色
* @param snackbar
* @param backgroundColor
*/
public static void setSnackbarColor(Snackbar snackbar, int backgroundColor) {
View view = snackbar.getView();
if(view!=null){
view.setBackgroundColor(backgroundColor);
}
}
/**
* 設定Snackbar文字和背景顏色
* @param snackbar
* @param messageColor
* @param backgroundColor
*/
public static void setSnackbarColor(Snackbar snackbar, int messageColor, int backgroundColor) {
View view = snackbar.getView();
if(view!=null){
view.setBackgroundColor(backgroundColor);
((TextView) view.findViewById(R.id.snackbar_text)).setTextColor(messageColor);
}
}
/**
* 向Snackbar中新增view
* @param snackbar
* @param layoutId
* @param index 新加布局在Snackbar中的位置
*/
public static void SnackbarAddView(Snackbar snackbar, int layoutId, int index) {
View snackbarview = snackbar.getView();
Snackbar.SnackbarLayout snackbarLayout=(Snackbar.SnackbarLayout)snackbarview;
View add_view = LayoutInflater.from(snackbarview.getContext()).inflate(layoutId,null);
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
p.gravity= Gravity.CENTER_VERTICAL;
snackbarLayout.addView(add_view,index,p);
}
}
複製程式碼
這個是從一個大神的專案中拿出來的,也挺不錯的,現在還沒用過 SnackBar 就真說不過去了!
ScreenUtils.java
public class ScreenUtils {
/**
* 獲得螢幕高度
* @param context
* @return
*/
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;
}
/**
* 獲得螢幕寬度
* @param context
* @return
*/
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;
}
/**
* 獲得狀態列的高度
* @param context
* @return
*/
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;
}
/**
* 獲取當前螢幕截圖,包含狀態列
* @param activity
* @return
*/
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 = null;
bp = Bitmap.createBitmap(bmp, 0, 0, width, height);
view.destroyDrawingCache();
return bp;
}
/**
* 獲取當前螢幕截圖,不包含狀態列
* @param activity
* @return
*/
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 = null;
bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height
- statusBarHeight);
view.destroyDrawingCache();
return bp;
}
}複製程式碼