现在的项目基本上已经完成一大半了,在这块把我所用到的所有工具类大概总结一下,方便以后以及大家使用
Example
JsonUtil(Jackson/Gson)
package com.aetos.utils;
import java.io.IOException;
import java.lang.reflect.Type;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import com.aetos.utils.ui.LogUtils;
import com.google.gson.Gson;
/**
* @author lpeng
* @update huangy
* @date 2015年8月21日
*/
public class JsonUtil {
//jsckson
public static <T extends Object>T jsonStr2JsonResult(String str,Class cl){
try {
return (T)new ObjectMapper().readValue(str, cl);
} catch (JsonParseException e) {
return null;
} catch (JsonMappingException e) {
return null;
} catch (IOException e) {
return null;
}
}
//Gson
public static <T> T json2Obj(String jsonString, Class<T> cls) {
T t = null;
try {
Gson gson = new Gson();
t = gson.fromJson(jsonString, cls);
} catch (Exception e) {
LogUtils.e("JsonUtil:"+e.toString());
}
return t;
}
public static String obj2Json(Object obj){
String str = null;
try {
Gson gson = new Gson();
str = gson.toJson(obj);
} catch (Exception e) {
LogUtils.e("JsonUtil:"+e.toString());
}
return str;
}
public static String toJson(Object obj, Type type) {
Gson gson = new Gson();
return gson.toJson(obj, type);
}
public static Object fromJson(String str,Type type){
Gson gson = new Gson();
return gson.fromJson(str, type);
}
/**
*
*
* Map转换层Bean,使用泛型免去了类型转换的麻烦。
*
* @param <T>
* @param map
* @param class1
* @return
*/
public static <T> T map2Obj(Map<String, Object> map, Class<T> clazz)
{
T t = null;
try
{
t = clazz.newInstance();
Method [] methods = clazz.getDeclaredMethods();
for (Method m : methods) {
if (m.getName().startsWith("set")) {
try
{
m.invoke(t, map.get(m.getName().replaceAll("set", "").toLowerCase()));
} catch (IllegalAccessException e)
{
e.printStackTrace();
} catch (IllegalArgumentException e)
{
e.printStackTrace();
} catch (InvocationTargetException e)
{
e.printStackTrace();
}
}
}
} catch (InstantiationException e1)
{
e1.printStackTrace();
} catch (IllegalAccessException e1)
{
e1.printStackTrace();
}
return t;
}
}
NumberUtil(个数话Number)
/**
*
*/
package com.aetos.utils;
import java.math.BigDecimal;
import java.text.DecimalFormat;
/**
* @author huangy
* @date 2015年8月12日
*/
public class NumberUtil
{
public static String formatNumWithDigits(int digits, double d)
{
String fomatString = "#0";
if (digits > 0)
{
fomatString = fomatString + ".";
}
for (int i = 1; i <= digits; i++)
{
fomatString = fomatString + "0";
}
DecimalFormat format = new DecimalFormat(fomatString);
return format.format(d);
}
/**
* 格式化为指定位小数的数字,返回未使用科学计数法表示的具有指定位数的字符串。
* 该方法舍入模式:向“最接近的”数字舍入,如果与两个相邻数字的距离相等,则为向上舍入的舍入模式。
*
* <pre>
* "3.1415926", 1 --> 3.1
* "3.1415926", 3 --> 3.142
* "3.1415926", 4 --> 3.1416
* "3.1415926", 6 --> 3.141593
* "1234567891234567.1415926", 3 --> 1234567891234567.142
* </pre>
*
* @param String类型的数字对象
* @param precision
* 小数精确度总位数,如2表示两位小数
* @return 返回数字格式化后的字符串表示形式(注意返回的字符串未使用科学计数法)
*/
public static String keepPrecision(String number, int precision)
{
BigDecimal bg = new BigDecimal(number);
return bg.setScale(precision, BigDecimal.ROUND_HALF_UP).toPlainString();
}
/**
* 格式化为指定位小数的数字,返回未使用科学计数法表示的具有指定位数的字符串。<br>
* 该方法舍入模式:向“最接近的”数字舍入,如果与两个相邻数字的距离相等,则为向上舍入的舍入模式。<br>
* 如果给定的数字没有小数,则转换之后将以0填充;例如:int 123 1 --> 123.0<br>
* <b>注意:</b>如果精度要求比较精确请使用 keepPrecision(String number, int precision)方法
*
* @param String类型的数字对象
* @param precision
* 小数精确度总位数,如2表示两位小数
* @return 返回数字格式化后的字符串表示形式(注意返回的字符串未使用科学计数法)
*/
public static String keepPrecision(Number number, int precision)
{
return keepPrecision(String.valueOf(number), precision);
}
/**
* 对double类型的数值保留指定位数的小数。<br>
* 该方法舍入模式:向“最接近的”数字舍入,如果与两个相邻数字的距离相等,则为向上舍入的舍入模式。<br>
* <b>注意:</b>如果精度要求比较精确请使用 keepPrecision(String number, int precision)方法
*
* @param number
* 要保留小数的数字
* @param precision
* 小数位数
* @return double 如果数值较大,则使用科学计数法表示
*/
public static double keepPrecision(double number, int precision)
{
BigDecimal bg = new BigDecimal(number);
return bg.setScale(precision, BigDecimal.ROUND_HALF_UP).doubleValue();
}
/**
* 对float类型的数值保留指定位数的小数。<br>
* 该方法舍入模式:向“最接近的”数字舍入,如果与两个相邻数字的距离相等,则为向上舍入的舍入模式。<br>
* <b>注意:</b>如果精度要求比较精确请使用 keepPrecision(String number, int precision)方法
*
* @param number
* 要保留小数的数字
* @param precision
* 小数位数
* @return float 如果数值较大,则使用科学计数法表示
*/
// public static float keepPrecision(float number, int precision)
// {
// BigDecimal bg = new BigDecimal(number);
// return bg.setScale(precision, BigDecimal.ROUND_HALF_UP).floatValue();
// }
public static String toFiexdstr(double value,int digit){
NumberFormat ddf=NumberFormat.getNumberInstance() ;
String result = "";
ddf.setMaximumFractionDigits(digit);
result = (ddf.format(value));
return result;
}
}
HandlerManager(Handler管理类)
/**
*
*/
package com.aetos.utils;
import java.util.HashMap;
import java.util.Map;
import android.os.Handler;
import android.os.Message;
/**
* @author lpeng
* @update huangy
* @date 2015年8月12日
*/
public class HandlerManager {
private static HandlerManager instance;
private static Map<String, Handler> map;
private HandlerManager() {
}
public static void init(){
if (instance == null) {
instance = new HandlerManager();
}
if(map == null){
map = new HashMap<String, Handler>();
}
}
public static HandlerManager getInstance() {
if (instance == null) {
instance = new HandlerManager();
}
return instance;
}
public static void addHandler(String action,Handler handler){
map.put(action, handler);
}
public static void sendMsg(String action,Object data){
Handler handler = map.get(action);
if(handler != null){
Message msg = Message.obtain();
msg.obj = data;
handler.sendMessage(msg);
}
}
public static void delMsg(String action){
map.remove(action);
}
public static boolean getMsg(String action)
{
return map.get(action) == null ? false:true;
}
}
Bean2Map(通过反射对象转换为Map)
/**
*
*/
package com.aetos.utils;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
/**
* @author lpeng
* @date 2015年4月13日
*/
public class BeanToMapUtil {
/*
* 将Object中对应的所有 属性-值 保存到Map集合中
*/
public static Map<String, Object> ConvertObjToMap(Object obj) {
Map<String, Object> reMap = new HashMap<String, Object>();
if (obj == null)
return null;
//获取实体类的所有属性,返回Field数组
Field[] fields = obj.getClass().getDeclaredFields();
try {
for (int i = 0; i < fields.length; i++) {
try {
//获取指定属性
// Field f = obj.getClass().getDeclaredField(
// fields[i].getName());
//直接便利获取属性
Field f = fields[i];
//设置该属性是否允许访问
f.setAccessible(true);
//获取属性值
Object o = f.get(obj);
reMap.put(fields[i].getName(), o);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return reMap;
}
}
DensityUtil(px sp dp 转换)
package com.aetos.utils.ui;
import android.content.Context;
import android.util.TypedValue;
/**
* @date 2015-07-24
* @author huangy
*/
public class DensityUtils {
/**
* dp TO px
* @param context
* @param val
* @return
*/
public static int dp2px(Context context, float dpVal){
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
dpVal, context.getResources().getDisplayMetrics());
}
/**
* sp TO px
* @param context
* @param val
* @return
*/
public static int sp2px(Context context, float spVal){
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
spVal, context.getResources().getDisplayMetrics());
}
/**
* px TO dp
* @param context
* @param pxVal
* @return
*/
public static float px2dp(Context context, float pxVal){
final float scale = context.getResources().getDisplayMetrics().density;
return (pxVal / scale);
}
/**
* px TO sp
* @param fontScale
* @param pxVal
* @return
*/
public static float px2sp(Context context, float pxVal){
return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);
}
}
FormatTextUtil(SpannableString的使用)
效果:
package com.aetos.utils.ui;
import android.graphics.Color;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.style.BackgroundColorSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.StyleSpan;
import android.text.style.SuperscriptSpan;
/**
*
* @author huangy
* @date 2015.11.16
*/
public class FormatTextUtils {
/*
* 截取allStr
* 设置 标准显示 高级显示
*/
public static String[] getStrArr(String allStr){
if(allStr == null || allStr.equals("")){
return new String[]{""};
}
int index = allStr.indexOf(".");
String strFirst = allStr.substring(0,index+1);
String strLast = allStr.substring(index+1,allStr.length());
String strSmall = "";
String strBig ="";
if(strLast.length() > 2){
strSmall = strLast.substring(strLast.length()-1, strLast.length());
strBig = strLast.substring(strLast.length()-3,strLast.length()-1);
strFirst = strFirst+strLast.substring(0,strLast.length()-3);
}else{
strBig = strLast.substring(0,strLast.length());
}
return new String[]{strFirst,strBig,strSmall};
}
/**
* 格式化字符串
* @param strs 传递过来的数据
* @param isUp 用于判断涨跌
*/
public static SpannableStringBuilder getBgBuilder(String[] strs,int isUp){
if(strs == null || strs.length < 3){
return null;
}
SpannableString builder1 = new SpannableString(strs[0]+" ");
SpannableStringBuilder builder = new SpannableStringBuilder();
SpannableString builder2;
builder2 = new SpannableString(" "+strs[1]+" ");
if(isUp == 2){
builder1.setSpan(new ForegroundColorSpan(Color.RED), 0, strs[0].length()+1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
builder2.setSpan(new BackgroundColorSpan(Color.RED), 0, strs[1].length()+2, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
builder2.setSpan(new ForegroundColorSpan(Color.WHITE), 0, strs[1].length()+2, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}else{
builder1.setSpan(new ForegroundColorSpan(Color.GREEN), 0, strs[0].length()+1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
builder2.setSpan(new BackgroundColorSpan(Color.GREEN), 0, strs[1].length()+2, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
builder2.setSpan(new ForegroundColorSpan(Color.BLACK), 0, strs[1].length()+2, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}
builder2.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, strs[1].length()+2, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
builder2.setSpan(new RelativeSizeSpan(1.3f), 0, strs[1].length()+2, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
builder.append(builder1).append(builder2);
builder1 = null;
builder2 = null;
return builder;
}
public static SpannableStringBuilder getSmallBuilder(String str,int isUp){
SpannableString spanStr = new SpannableString(str);
if(isUp == 2){
spanStr.setSpan(new ForegroundColorSpan(Color.RED), 0, str.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}else{
spanStr.setSpan(new ForegroundColorSpan(Color.GREEN), 0, str.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}
SpannableStringBuilder builder = new SpannableStringBuilder();
return builder.append(spanStr);
}
/*
* 截取allStr
* Traditional
*/
public static String[] getTraArr(String allStr){
if(allStr == null || allStr.equals("0")){
return new String[]{"0","0"};
}
int index = allStr.indexOf(".");
//小数点前
String strFirst = null;
String strLast = null;
if(index == -1){
strFirst = allStr.substring(0, allStr.length() - 1);
strLast = allStr.substring(allStr.length() - 1, allStr.length());
return new String[]{strFirst,strLast};
}
//小数点后
strLast = allStr.substring(index+1,allStr.length());
if(strLast.length() == 1){
strFirst = allStr.substring(0, index);
strLast = allStr.replaceAll("\\d+\\.", "");
}
if(strLast.length() == 2){
strFirst = allStr.substring(0,index+1);
}else if(strLast.length() >= 3){
strFirst = allStr.substring(0,allStr.length()-3);
strLast = allStr.substring(allStr.length()-3,allStr.length());
}
return new String[]{strFirst,strLast};
}
/**
* 格式化字体 背景色 右上角小标
* 不适应顶部对齐
*/
public static SpannableStringBuilder formatText(String str){
String[] strs = str.split("/");
SpannableString builder1 = new SpannableString(strs[0]);
builder1.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, strs[0].length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
builder1.setSpan(new RelativeSizeSpan(1.2f), 0, strs[1].length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
SpannableString builder2 = new SpannableString(strs[1]);
SpannableStringBuilder builder = new SpannableStringBuilder();
return builder.append(builder1).append(builder2);
}
public static SpannableStringBuilder getBuilder(String[] strs,int color){
if(strs == null || strs.length < 3){
return null;
}
SpannableString builder1 = new SpannableString(strs[0]);
SpannableString builder2;
SpannableStringBuilder builder = new SpannableStringBuilder();
builder1.setSpan(new ForegroundColorSpan(color), 0, strs[0].length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
builder2 = new SpannableString(strs[1]);
builder2.setSpan(new ForegroundColorSpan(color), 0, strs[1].length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
builder2.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, strs[1].length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
builder2.setSpan(new RelativeSizeSpan(1.3f), 0, strs[1].length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
builder.append(builder1).append(builder2);
if(strs.length == 3){
SpannableString builder3 = new SpannableString(strs[2]);
builder3.setSpan(new SuperscriptSpan(), 0, strs[2].length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
builder3.setSpan(new ForegroundColorSpan(color), 0, strs[2].length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
builder3.setSpan(new RelativeSizeSpan(0.6f), 0, strs[2].length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
builder.append(builder3);
builder3 = null;
}
builder1 = null;
builder2 = null;
return builder;
}
}
LogUtil(Log日志打印工具类)
package com.aetos.utils.ui;
import android.util.Log;
/**
* @date 2015-07-24
* @author huangy
*/
public class LogUtils {
private LogUtils(){
throw new UnsupportedOperationException("LogUtils can't be instantiated");
}
public static boolean isDebug = true;
private static final String TAG = "way";
public static void i(String msg){
if(isDebug)
Log.i(TAG, msg);
}
public static void d(String msg){
if(isDebug)
Log.d(TAG, msg);
}
public static void e(String msg){
if(isDebug)
Log.e(TAG, msg);
}
public static void v(String msg){
if(isDebug)
Log.v(TAG, msg);
}
public static void i(String tag,String msg){
if(isDebug)
Log.i(tag, msg);
}
public static void d(String tag,String msg){
if(isDebug)
Log.d(tag, msg);
}
public static void e(String tag,String msg){
if(isDebug)
Log.e(tag, msg);
}
public static void v(String tag,String msg){
if(isDebug)
Log.v(tag, msg);
}
}
NetUtils(网络监听)
package com.aetos.utils.ui;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
/**
*
* @author huangy
* @date 2015.9.12
*/
public class NetUtils {
// 判断网络连接状态
public static boolean isNetworkConnected(Context context) {
if (context != null) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo net = connectivityManager
.getActiveNetworkInfo();
if (net != null) {
return net.isAvailable();
}
}
return false;
}
// 判断wifi状态
public static boolean isWifiConnected(Context context) {
if (context != null) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiNet = connectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (wifiNet != null && isNetworkConnected(context)) {
return wifiNet.isAvailable();
}
}
return false;
}
// 判断移动网络
public static boolean isMobileConnected(Context context) {
if (context != null) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mobileNet = connectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (mobileNet != null && isNetworkConnected(context)) {
return mobileNet.isAvailable();
}
}
return false;
}
// 获取连接类型
public static int getConnectedType(Context context) {
if (context != null) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo net = connectivityManager
.getActiveNetworkInfo();
if (net != null && net.isAvailable()) {
return net.getType();
}
}
return -1;
}
}
ScreenUtil(屏幕px)
package com.aetos.utils.ui;
import android.content.Context;
import android.util.DisplayMetrics;
import android.view.WindowManager;
/**
* @date 2015-07-24
* @author huangy
*/
public class ScreenUtils {
private ScreenUtils(){
throw new UnsupportedOperationException("Screen can't be instantiated");
}
/**
* get ScreenHeight px
* @param context
* @return
*/
public static float getScreenHeight(Context context){
WindowManager manager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics metrics = new DisplayMetrics();
manager.getDefaultDisplay().getMetrics(metrics);
return metrics.heightPixels;
}
/**
* get ScreenWidth px
* @param context
* @return
*/
public static float getScreenWidth(Context context){
WindowManager manager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics metrics = new DisplayMetrics();
manager.getDefaultDisplay().getMetrics(metrics);
return metrics.widthPixels;
}
/**
* get statusHeight px
* @param context
* @return
*/
public static float 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;
}
}
SDCardUtils
package com.aetos.utils.ui;
import java.io.File;
import android.os.Environment;
import android.os.StatFs;
/**
* @date 2015-07-24
* @author huangy
*/
public class SDCardUtils {
private SDCardUtils(){
/* cannot be instantiated */
throw new UnsupportedOperationException("SDCardUtils can't be instantiated");
}
/**
* Judge the SDCard is available
* @return
*/
public static boolean isSDCardEnable(){
return Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
}
/**
* get SDCard path
* @return
*/
public static String getSDCardPath(){
return Environment.getExternalStorageDirectory().getAbsolutePath()
+ File.separator;
}
/**
*Access to SD card remaining capacity 单位byte
* @return
*/
public static long getSDCardAllSize(){
if (isSDCardEnable()){
StatFs stat = new StatFs(getSDCardPath());
// For the rest of the free data block size
long availableBlocks = (long) stat.getAvailableBlocks() - 4;
// The size of the access to a single block of data(byte)
long freeBlocks = stat.getAvailableBlocks();
return freeBlocks * availableBlocks;
}
return 0;
}
/**
* Access files in the path of the remaining space 单位byte
* @param filePath
* @return SDCard's available
* inCard's available
*/
public static long getFreeBytes(String filePath){
// if sdCard,get sdCard count
if (filePath.startsWith(getSDCardPath())){
filePath = getSDCardPath();
}else{
//if inCard,get inCard count
filePath = Environment.getDataDirectory().getAbsolutePath();
}
StatFs stat = new StatFs(filePath);
long availableBlocks = (long) stat.getAvailableBlocks() - 4;
return stat.getBlockSize() * availableBlocks;
}
/**
* get Root Path
* @return
*/
public static String getRootDirectoryPath(){
return Environment.getRootDirectory().getAbsolutePath();
}
}
SharedPreferencesUtil
package com.aetos.utils.ui;
import android.content.Context;
import android.content.SharedPreferences;
/**
* @date 2015-07-24
* @author huangy
*/
public class SharedPreferencesUtils {
private static String fileName = "";
/* 用于设置SharedPreferences文件名称 */
public static void setFileName(String name){
fileName = name;
}
/*
* 用于设置存储参数
* 根据数据,判断类型,选取对应方法,进行粗出
* @param key 键名
* @param obj 数据
*/
public static void setParam(SharedPreferences sp,String key,Object obj){
String type = obj.getClass().getSimpleName();
SharedPreferences.Editor editor = sp.edit();
if("String".equals(type)){
editor.putString(key, (String)obj);
}
else if("Integer".equals(type)){
editor.putInt(key, (Integer)obj);
}
else if("Boolean".equals(type)){
editor.putBoolean(key, (Boolean)obj);
}
else if("Float".equals(type)){
editor.putFloat(key, (Float)obj);
}
else if("Long".equals(type)){
editor.putLong(key, (Long)obj);
}
editor.commit();
}
/*
* get SharedPreferences
*/
public static SharedPreferences getSp(Context context,String fileName){
return context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
}
/*
* 根据key获取对应的数据,调用相对应的方法
* @param key 键名
* @param obj 默认值
*/
public static Object getParam(SharedPreferences sp,String key,Object obj){
String type = obj.getClass().getSimpleName();
if("String".equals(type)){
return sp.getString(key, (String)obj);
}
else if("Integer".equals(type)){
return sp.getInt(key, (Integer)obj);
}
else if("Boolean".equals(type)){
return sp.getBoolean(key, (Boolean)obj);
}
else if("Float".equals(type)){
return sp.getFloat(key, (Float)obj);
}
else if("Long".equals(type)){
return sp.getLong(key, (Long)obj);
}
return null;
}
}
ToastUtils
package com.aetos.utils.ui;
import android.content.Context;
import android.widget.Toast;
/**
* @date 2015-07-24
* @author huangy
*/
public class ToastUtils {
private ToastUtils(){
throw new UnsupportedOperationException("ToastUtils can't be instantiated");
}
public static boolean isShow = true;
/**
* LENGTH_SHORT
* @param context
* @param msg
*/
public static void showShort(Context context,CharSequence msg){
if(isShow)
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
}
/**
* LENGTH_SHORT
* @param context
* @param msg
*/
public static void showShort(Context context,int msg){
if(isShow)
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
}
/**
* LENGTH_LONG
* @param context
* @param msg
*/
public static void showLong(Context context,CharSequence msg){
if(isShow)
Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
}
/**
* LENGTH_LONG
* @param context
* @param msg
*/
public static void showLong(Context context,int msg){
if(isShow)
Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
}
/**
* Cust Time
* @param context
* @param msg
* @param duration
*/
public static void show(Context context,CharSequence msg,int duration){
if(isShow)
Toast.makeText(context, msg, duration).show();
}
/**
* Cust Time
* @param context
* @param msg
* @param duration
*/
public static void show(Context context,int msg,int duration){
if(isShow)
Toast.makeText(context, msg, duration).show();
}
}
ViewHolder(应用于adapter)
package com.aetos.utils.ui;
import android.util.SparseArray;
import android.view.View;
/**
* ViewHolder Common
* to Adapter
* @author huangy
* @date 2015-07-27
*/
public class ViewHolder {
/*
* Java泛型属于伪泛型,编译后进行'类型擦出'
* public static <T extends View> T getView(View view,int id)
* 泛型方法,实现多态 传递数据为 View或者View子类,不需要强转
* <T extends View> 原始类型:View
* <T> 原始类型:Object
* List<String>(各种类型) 原始类型:编译之后,类型擦出,原始类型 Object,或取 所有数据的父类最小级
* arrayList3.getClass().getMethod("add", Object.class).invoke(arrayList3, "asd");
* 通过反射机制,忽略泛型限制
*/
//method1:
public static <T extends View> T getView(View view,int id){
/*
* viewHolder to save childView
*/
SparseArray<View> viewHolder = (SparseArray<View>)view.getTag();
if(viewHolder == null){
viewHolder = new SparseArray<View>();
view.setTag(viewHolder);
}
View childView = viewHolder.get(id);
if(childView == null){
childView = view.findViewById(id);
viewHolder.put(id, childView);
}
return (T)childView;
}
//method2:
// private final SparseArray<View> views;
// private View convertView;
// private ViewHolder(View convertView){
// this.views = new SparseArray<View>();
// this.convertView = convertView;
// convertView.setTag(this);
// }
// /**
// * add ChildView and return
// * @param id
// * @return
// */
// public <T extends View> T getView(int id){
// View view = views.get(id);
// if(view == null){
// view = convertView.findViewById(id);
// views.put(id, view);
// }
// return (T)view;
// }
// public static ViewHolder get(View convertView){
// if(convertView == null){
// return new ViewHolder(convertView);
// }
// ViewHolder holder = (ViewHolder)convertView.getTag();
// return holder;
// }
}
ByteUtil
/**
*
*/
package com.aetos.utils;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* @author lpeng
* @date 2015年4月7日
*/
public class ByteUtil {
public static byte[] arrayCopy(byte[] sourceArray, int startSource,
byte[] targetArray, int startTarget, int size) {
for (int i = 0; i < size; i++) {
targetArray[startTarget + i] = sourceArray[startSource + i];
}
return targetArray;
}
public static void printByteArray(byte[] array) {
for (int i = 0; i < array.length; i++)
System.out.println("array[" + i + "]=" + array[i]);
}
public static int decodeShort(byte[] byteBuf, int pos) {
byte[] buf = new byte[2];
arrayCopy(byteBuf, pos, buf, 0, 2);
return (buf[0] & 0xff) | (buf[1] & 0xff) << 8;
}
public static int decodeInt(byte[] byteBuf, int pos) {
byte[] buf = new byte[4];
arrayCopy(byteBuf, pos, buf, 0, 4);
return (buf[0] & 0xff) | (buf[1] & 0xff) << 8 | (buf[2] & 0xff) << 16
| (buf[3] & 0xff) << 24;
}
public static double decodeDouble(byte[] byteBuf, int pos) {
byte[] b = new byte[8];
arrayCopy(byteBuf, pos, b, 0, 8);
long l;
l = b[0];
l &= 0xff;
l |= ((long) b[1] << 8);
l &= 0xffff;
l |= ((long) b[2] << 16);
l &= 0xffffff;
l |= ((long) b[3] << 24);
l &= 0xffffffffl;
l |= ((long) b[4] << 32);
l &= 0xffffffffffl;
l |= ((long) b[5] << 40);
l &= 0xffffffffffffl;
l |= ((long) b[6] << 48);
l &= 0xffffffffffffffl;
l |= ((long) b[7] << 56);
return Double.longBitsToDouble(l);
}
public static long decodeLong8(byte[] byteBuf,int pos) {
byte[] bytes = new byte[8];
arrayCopy(byteBuf, pos, bytes, 0, 8);
return (0xffL & (long) bytes[0]) | (0xff00L & ((long) bytes[1] << 8))
| (0xff0000L & ((long) bytes[2] << 16))
| (0xff000000L & ((long) bytes[3] << 24))
| (0xff00000000L & ((long) bytes[4] << 32))
| (0xff0000000000L & ((long) bytes[5] << 40))
| (0xff000000000000L & ((long) bytes[6] << 48))
| (0xff00000000000000L & ((long) bytes[7] << 56));
}
public static long decodeLong4(byte[] byteBuf,int pos) {
byte[] bytes = new byte[4];
arrayCopy(byteBuf, pos, bytes, 0, 4);
return (0xffL & (long) bytes[0]) | (0xff00L & ((long) bytes[1] << 8))
| (0xff0000L & ((long) bytes[2] << 16))
| (0xff000000L & ((long) bytes[3] << 24)
);
}
public static int decodeChar(byte[] byteBuf,int pos) {
byte[] b = new byte[1];
arrayCopy(byteBuf, pos, b, 0, 1);
// char c = (char) (((b[0] & 0xFF) << 8) | (b[1] & 0xFF));
int c = b[0];
return c;
}
public static String decodeStr(byte[] byteBuf, int pos, int len) {
byte[] b = new byte[len];
arrayCopy(byteBuf, pos, b, 0, len);
return new String(b, Charset.forName("UTF-8"));
}
public static int encodeInt(byte[] byteBuf, int pos, int value) {
byteBuf[pos++] = (byte) (value & 0xff);
byteBuf[pos++] = (byte) (value >> 8 & 0xff);
byteBuf[pos++] = (byte) (value >> 16 & 0xff);
byteBuf[pos++] = (byte) (value >> 24 & 0xff);
return pos;
}
public static int encodeShort(byte[] byteBuf, int pos, int value) {
byteBuf[pos++] = (byte) (value & 0xff);
byteBuf[pos++] = (byte) (value >> 8 & 0xff);
return pos;
}
public static int encodeString(byte[] byteBuf, int pos, String value,
int len) {
byte[] temp = null;
try {
temp = value.getBytes("UTF-8");
arrayCopy(temp, 0, byteBuf, pos, temp.length);
pos += temp.length;
for (int m = temp.length; m < len; m++) {
byteBuf[pos++] = 0;
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return pos;
}
public static int encodeDouble(byte[] byteBuf,int pos,double value){
long v = Double.doubleToLongBits(value);
byteBuf[pos++] = (byte)(v >>> 56);
byteBuf[pos++] = (byte)(v >>> 48);
byteBuf[pos++] = (byte)(v >>> 40);
byteBuf[pos++] = (byte)(v >>> 32);
byteBuf[pos++] = (byte)(v >>> 24);
byteBuf[pos++] = (byte)(v >>> 16);
byteBuf[pos++] = (byte)(v >>> 8);
byteBuf[pos++] = (byte)(v >>> 0);
return pos;
}
public static String getFormatTime(long unixTime) {
Long timestamp = (long) ((unixTime) * 1000);
Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timestamp);
date.setTime(timestamp);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String str_date = sdf.format(cal.getTime());
// String date = new
// java.text.SimpleDateFormat("yyyy-dd-mm HH:mm:ss").format(new
// java.util.Date(timestamp));
return str_date;
}
/**********************************************************************************************/
/**
* 返回当前日期前指定天数的时间戳(UNIX格式,如1400724257)
*
* @param value
* @return
*
*/
public static int getDateBefore(int value) {
Date beginDate = new Date();
Calendar date = Calendar.getInstance();
date.setTime(beginDate);
date.set(Calendar.DATE, date.get(Calendar.DATE) - value);
return Math.round(date.getTimeInMillis() / 1000);
}
}