Android 常用工具类转换

     Android 常用单位转换的工具类

1. 常用单位转换的工具类

/**
 * 常用单位转换的工具类
 */
public class ViewUtil {
    private ViewUtil() {
        /** cannot be instantiated **/
        throw new UnsupportedOperationException("cannot be instantiated");
    }

    private static int screenWidthPixels;
    private static int screenHeightPixels;

    /**
     * dp转px
     *
     * @param context
     * @param dpVal
     * @return
     */
    public static int dp2px(Context context, float dpVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                dpVal, context.getResources().getDisplayMetrics());
    }

    /**
     * sp转px
     *
     * @param context
     * @param spVal
     * @return
     */
    public static int sp2px(Context context, float spVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
                spVal, context.getResources().getDisplayMetrics());
    }

    /**
     * px转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转sp
     *
     * @param pxVal
     * @param pxVal
     * @return
     */
    public static float px2sp(Context context, float pxVal) {
        return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);
    }

    /**
     * @param context
     * @return
     */
    public static int getScreenWidthPixels(Context context) {

        if (context == null) {
            return 0;
        }

        if (screenWidthPixels > 0) {
            return screenWidthPixels;
        }
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        manager.getDefaultDisplay().getMetrics(dm);
        screenWidthPixels = dm.widthPixels;
        return screenWidthPixels;
    }

    /**
     * @param context
     * @return
     */
    public static int getScreenHeightPixels(Context context) {
        if (context == null) {
            return 0;
        }

        if (screenHeightPixels > 0) {
            return screenHeightPixels;
        }
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        manager.getDefaultDisplay().getMetrics(dm);
        screenHeightPixels = dm.heightPixels;
        return screenHeightPixels;
    }
}

2.常用工具类转换设置等

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.luck.picture.lib.tools.StringUtils;
import com.southsummer.goddessplan.R;
import com.southsummer.goddessplan.bean.FindDynamicByKeywordsBean;
import com.southsummer.goddessplan.bean.GetDynamicByTypeBean;
import com.southsummer.goddessplan.bean.MapGroupDynamicBean;
import com.southsummer.goddessplan.bean.OriginalAllBean;
import com.southsummer.goddessplan.bean.VideoDynamicBean;
import com.southsummer.goddessplan.ui.activities.WelcomeActivity;
import com.southsummer.goddessplan.ui.activities.language.LanguageType;
import com.southsummer.goddessplan.ui.activities.language.MultiLanguageUtil;

import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * Created by zego on 2019/1/8.
 */

public class StringUtil {

    private static int counter;
    public static boolean isEmpty(String str) {
        return null == str || str.trim().equals("");
    }

    public static String replaceBlank(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

    /**
     * 设置textView拼接颜色
     */
    public static String setStrRed(String str) {
        return "<font color='red'>" + str + "</font>";
    }

    //白色
    public static String setStrWhite(String str) {
        return "<font color='#ffffff'>" + str + "</font>";
    }

    //蓝色
    public static String setStrBlue(String str) {
        return "<font color='#6FA0F8'>" + str + "</font>";
    }

    public static String setStrMainRed(String str) {
        return "<font color='#f33b3b'>" + str + "</font>";
    }

    //灰色
    public static String setStrGray(String str) {
        return "<font color='#888888'>" + str + "</font>";
    }

    //灰色2
    public static String setStrGray2(String str) {
        return "<font color='#999999'>" + str + "</font>";
    }

    /**
     * 截取手机号码中间四位*显示
     *
     * @return str1
     */
    public static String showPhonenumber(String str) {
        // TODO SGF ADD
        String a = "";
        a = str.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
        return a;
    }

    /**
     * Java 使用手机号码判断
     */
    public static final String PHONE_NUMBER_REG =  "^((13[0-9])|(15[^4])|(166)|(17[0-8])|(18[0-9])|(19[8-9])|(147,145))\\d{8}$";
//    String PHONE_NUMBER_REG = "^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$";
    //手机号
//    public static final String phoneNum = "^((13[0-9])|(16[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
    public static final String phoneNum = "^[1][3,4,5,7,8,9][0-9]{9}$";
    //常规密码 允许纯字母 数字等
    public static final String password = "^[a-zA-Z0-9]{6,12}$";
    //6-20位,包含字母、数字、符号其中2种
    public static final String password1 = "^(?![\\d]+$)(?![a-zA-Z]+$)(?![^\\da-zA-Z]+$).{6,20}$";
    public static final String password2 = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,21}$";
    public static final String password5 = "^(?![\\d]+$){6,21}$";
    //限定特殊字符,6-20位,包含字母、数字、符号其中2种
    public static final String password3 = "^(?![\\d]+$)(?![a-zA-Z]+$)(?![!#$%^&*]+$)[\\da-zA-Z!#$%^&*]{6,20}$";
    ///^[a-zA-Z0-9\x21-\x7e]{6,20}$/
    //用户名
    public static final String userName = "^[\\w\\u4e00-\\u9fa5]{3,20}$";
    //Email
    public static final String emails = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
    //验证码
    public static final String captchas = "^[0-9A-Za-z]{4,6}$";
    //银行卡号
    public static final String bankCards = "^(\\d{16}|\\d{19})$";
    //身份证号
    public static final String idCards = "^(\\d{15}$|^\\d{18}$|^\\d{17}(\\d|X|x))$";

    /**
     * 验证手机号
     *
     * @param str 手机号码
     * @return true--正确,false--错误
     */
    public static boolean isPhoneNum(String str) {
        Pattern p = Pattern
                .compile(PHONE_NUMBER_REG);

        Matcher m = p.matcher(str);

        return m.matches();
    }
    /**
     * 大陆号码或香港、澳门、台湾号码均可
     */
    public static boolean isPhoneLegal(String str)throws PatternSyntaxException {
        return isPhoneNum(str) || isHKPhoneLegal(str) || isTaiwanPhoneLegal(str);
    }

    /**
     * 大陆手机号码11位数,匹配格式:前三位固定格式+后8位任意数
     * 此方法中前三位格式有:
     * 13+任意数
     * 15+除4的任意数
     * 18+除1和4的任意数
     * 17+除9的任意数
     * 147
     */
    public static boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {
        String regExp = "^((13[0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }

    /**
     * 香港手机号码8位数,5|6|8|9开头+7位任意数
     * 香港: 国家码为852,手机号规则: 首位为5|6|8|9 后面接7位数字,一共8位数。
     *澳门:国家码为853,手机号规则: 首位为6 后面接7位数字,一个8位数。
     */
    public static boolean isHKPhoneLegal(String str)throws PatternSyntaxException {
        String regExp = "^(5|6|8|9|09)\\d{7}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }

    /**
     * 台湾:国家码为886 ,手机号规则: 首位为9|09 后面接8位数字。一个9位或10位数字。
     * @param str
     * @return
     * @throws PatternSyntaxException
     */
    public static boolean isTaiwanPhoneLegal(String str)throws PatternSyntaxException {
        String regExp = "^(9|09)\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }

    /**
     * 验证密码
     *
     * @param str 密码
     * @return true--正确,false--错误
     */
    public static boolean isPassword(String str) {
        Pattern p = Pattern.compile(password1);
        Matcher m = p.matcher(str);
        return m.matches();
    }
    /**
     * 验证普通密码
     *
     * @param str 密码
     * @return true--正确,false--错误
     */
    public static boolean isPasswordNum(String str) {
        int length = str.length();
        if(str.length()>=6 && str.length()<=20){
            return true;
        }else {
            return false;
        }
    }

    /**
     * 验证用户名
     *
     * @param str 用户名
     * @return true--正确,false--错误
     */
    public static boolean isUsername(String str) {
        String patternStr = userName;
        Pattern p = Pattern.compile(patternStr);
        Matcher m = p.matcher(str);
        return m.matches();
    }

    /**
     * 验证邮箱
     *
     * @param email 邮箱
     * @return true--正确,false--错误
     */
    public static boolean isEmail(String email) {
        String str = emails;
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(email);
        return m.matches();
    }

    /**
     * 验证验证码
     *
     * @param captcha 验证码
     * @return true--正确,false--错误
     */
    public static boolean isCaptcha(String captcha) {
        Pattern p = Pattern.compile(captchas);
        Matcher m = p.matcher(captcha);
        return m.matches();
    }

    /**
     * 验证银行卡号
     *
     * @return
     */
    public static boolean isBankCard(String bankCard) {
        Pattern compile = Pattern.compile(bankCards);
        Matcher matcher = compile.matcher(bankCard);
        return matcher.matches();
    }

    /**
     * 验证身份证号
     *
     * @param idCard
     * @return
     */
    public static boolean isIdCard(String idCard) {
        Pattern compile = Pattern.compile(idCards);
        Matcher matcher = compile.matcher(idCard);
        return matcher.matches();

    }

    /**
     * 保留两位小数
     */
    public static String keepTwoDecimals(double v) {
        DecimalFormat format = new DecimalFormat("0.0");
        return format.format(v);
    }

    public static String decimalFormat(double v, String type) {
        DecimalFormat format = new DecimalFormat(type);
        return format.format(v);
    }

    /**
     * 千分号
     *
     * @param price
     * @param halfUp
     * @return
     */
    public static String formatPrice(double price, boolean halfUp) {
        DecimalFormat formater = new DecimalFormat();
        // keep 2 decimal places
        formater.setMaximumFractionDigits(2);
        formater.setGroupingSize(3);
        formater.setRoundingMode(halfUp ? RoundingMode.HALF_UP : RoundingMode.FLOOR);
        return formater.format(price);
    }

    public static String formatPrice(int price) {
        DecimalFormat formater = new DecimalFormat();
        // keep 2 decimal places
        formater.setMaximumFractionDigits(0);
        formater.setGroupingSize(3);
        return formater.format(price);
    }

    /**
     * 设置键盘隐藏
     *
     * @param activity
     */
    public static void setSoftKeyboardHide(Activity activity) {
        //若键盘显示则隐藏键盘
        if (SoftKeyboardUtils.isSoftShowing(activity)) {
            SoftKeyboardUtils.hideSoftKeyboard(activity);
        }
    }

    /**
     * 设置键盘显示
     *
     * @param activity
     */
    public static void setSoftKeyboardShow(Activity activity) {
        //若键盘显示则隐藏键盘
        if (!SoftKeyboardUtils.isSoftShowing(activity)) {
            SoftKeyboardUtils.showSoftKeyboard(activity);
        }
    }

    /**
     * 设置键盘显示
     *
     * @param editText
     */
    public static void showSoftInputFromWindow(EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        InputMethodManager inputManager =
                (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(editText, 0);
    }

    /**
     * 设置列表中的数据循环遍历赋值(关注状态)
     *
     * @param dataList 集合
     * @param position 下标
     */
    public static void setFollowState(List<GetDynamicByTypeBean.DataBean.DynamicsBean> dataList, int position, int type) {
        //循环遍历
        for (int i = 0; i < dataList.size(); i++) {
            if (dataList.get(i).getUserId().equals(dataList.get(position).getUserId())) {
                if (type == 1) {
                    dataList.get(i).setIsFollow("1");
                } else {
                    dataList.get(i).setIsFollow("0");
                }
            }
        }
    }

    /**
     * 设置列表中的数据循环遍历赋值(关注状态)
     *
     * @param dataList 集合
     * @param position 下标
     */
    public static void setPictureFollowState(List<MapGroupDynamicBean.DataBean.DynamicsBean> dataList, int position, int type) {
        //循环遍历
        for (int i = 0; i < dataList.size(); i++) {
            if (dataList.get(i).getUserId().equals(dataList.get(position).getUserId())) {
                if (type == 1) {
                    dataList.get(i).setIsFollow("1");
                } else {
                    dataList.get(i).setIsFollow("0");
                }
            }
        }
    }

    /**
     * 设置列表中的数据循环遍历赋值(关注状态)
     *
     * @param dataList 集合
     * @param position 下标
     */
    public static void setVideoFollowState(List<OriginalAllBean.DataBean.DynamicsBean> dataList, int position, int type) {
        //循环遍历
        for (int i = 0; i < dataList.size(); i++) {
            if (dataList.get(i).getUserId().equals(dataList.get(position).getUserId())) {
                if (type == 1) {
                    dataList.get(i).setIsFollow("1");
                } else {
                    dataList.get(i).setIsFollow("0");
                }
            }
        }
    }

    /**
     * 设置列表中的数据循环遍历赋值(关注状态)  搜索用户动态的关注设置
     *
     * @param dataList 集合
     * @param position 下标
     */
    public static void setSearchDynamicFollowState(List<FindDynamicByKeywordsBean.DataBean.DynamicsBean> dataList, int position, int type) {
        //循环遍历
        for (int i = 0; i < dataList.size(); i++) {
            if (dataList.get(i).getUserId().equals(dataList.get(position).getUserId())) {
                if (type == 1) {
                    dataList.get(i).setIsFollow("1");
                } else {
                    dataList.get(i).setIsFollow("0");
                }
            }
        }
    }

    /**
     * 设置列表中的数据循环遍历赋值(关注状态)-原创
     *
     * @param dataList 集合
     * @param position 下标
     */
    public static void setOriginalFollowState(List<OriginalAllBean.DataBean.DynamicsBean> dataList, int position, int type) {
        //循环遍历
        for (int i = 0; i < dataList.size(); i++) {
            if (dataList.get(i).getUserId().equals(dataList.get(position).getUserId())) {
                if (type == 1) {
                    dataList.get(i).setIsFollow("1");
                } else {
                    dataList.get(i).setIsFollow("0");
                }
            }
        }
    }

    /**
     * 设置列表中的数据循环遍历赋值(关注状态)-媚影视频
     *
     * @param dataList 集合
     * @param position 下标
     */
    public static void setSlidVideoFollowState(List<VideoDynamicBean.DataBean.RankVideoBean> dataList, int position, int type) {
        //循环遍历
        for (int i = 0; i < dataList.size(); i++) {
            if (dataList.get(i).getUserId().equals(dataList.get(position).getUserId())) {
                if (type == 1) {
                    dataList.get(i).setIsFollow("1");
                } else {
                    dataList.get(i).setIsFollow("0");
                }
            }
        }
    }

    /**
     * 设置列表中的数据循环遍历赋值(根据动态id设置关注状态)-原创
     *
     * @param dataList  集合
     * @param dynamicid 用户动态id
     * @param type      是否关注
     */
    public static void setOriginalFollowStateOfDynamid(List<OriginalAllBean.DataBean.DynamicsBean> dataList, int dynamicid, int type,int po) {
        //循环遍历
        for (int i = 0; i < dataList.size(); i++) {
            if (dataList.get(i).getId() == dynamicid) {
                if (type == 1) {
                    dataList.get(i).setIsFollow("1");
                } else {
                    dataList.get(i).setIsFollow("0");
                }
            }
            if (dataList.get(i).getUserId().equals(dataList.get(po).getUserId())) {
                if (type == 1) {
                    dataList.get(i).setIsFollow("1");
                } else {
                    dataList.get(i).setIsFollow("0");
                }
            }
        }
    }

    /**
     * 设置列表中的数据循环遍历赋值(根据动态id设置关注状态)-媚影视频
     *
     * @param dataList  集合
     * @param dynamicid 用户动态id
     * @param type      是否关注
     */
    public static void setSlideVideoFollowStateOfDynamid(List<VideoDynamicBean.DataBean.RankVideoBean> dataList, int dynamicid, int type,int po) {
        //循环遍历
        for (int i = 0; i < dataList.size(); i++) {
            if (dataList.get(i).getId() == dynamicid) {
                if (type == 1) {
                    dataList.get(i).setIsFollow("1");
                } else {
                    dataList.get(i).setIsFollow("0");
                }
            }
            if (dataList.get(i).getUserId().equals(dataList.get(po).getUserId())) {
                if (type == 1) {
                    dataList.get(i).setIsFollow("1");
                } else {
                    dataList.get(i).setIsFollow("0");
                }
            }
        }
    }

    /**
     * <pre>
     * 数字格式化显示
     * 小于万默认显示 大于万以1.7万方式显示最大是9999.9万
     * 大于亿以1.1亿方式显示最大没有限制都是亿单位
     * make by dongxh 2017年12月28日上午10:05:22
     * </pre>
     *
     * @param num   格式化的数字
     * @param kBool 是否格式化千,为true,并且num大于999就显示999+,小于等于999就正常显示
     * @return
     */
    public static String formatNum(String num, Boolean kBool ) {
        StringBuffer sb = new StringBuffer();
        if (!StringUtil.isNumeric(num))
            return "0";
        if (kBool == null)
            kBool = false;

        BigDecimal b0 = new BigDecimal("1000");
        BigDecimal b1 = new BigDecimal("10000");
        BigDecimal b2 = new BigDecimal("100000000");
        BigDecimal b3 = new BigDecimal(num);

        String formatNumStr = "";
        String nuit = "";

        // 以千为单位处理
        if (kBool) {
            if (b3.compareTo(b0) == 0 || b3.compareTo(b0) == 1) {
                return "999+";
            }
            return num;
        }

        // 以万为单位处理
        if (b3.compareTo(b1) == -1) {
            sb.append(b3.toString());
        } else if ((b3.compareTo(b1) == 0 && b3.compareTo(b1) == 1)
                || b3.compareTo(b2) == -1) {
            formatNumStr = b3.divide(b1).toString();
            nuit = AppUtils.getContext().getString(R.string.ten_thousand);
        } else if (b3.compareTo(b2) == 0 || b3.compareTo(b2) == 1) {
            formatNumStr = b3.divide(b2).toString();
            nuit = AppUtils.getContext().getString(R.string.billion);
        }
        if (!"".equals(formatNumStr)) {
            int i = formatNumStr.indexOf(".");
            if (i == -1) {
                sb.append(formatNumStr).append(nuit);
            } else {
                i = i + 1;
                String v = formatNumStr.substring(i, i + 1);
                if (!v.equals("0")) {
                    sb.append(formatNumStr.substring(0, i + 1)).append(nuit);
                } else {
                    sb.append(formatNumStr.substring(0, i - 1)).append(nuit);
                }
            }
        }
        if (sb.length() == 0)
            return "0";
        return sb.toString();
    }

    /**
     * 判断是否是数字
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        if (str == null) {
            return false;
        }
        int sz = str.length();
        for (int i = 0; i < sz; i++) {
            if (Character.isDigit(str.charAt(i)) == false) {
                return false;
            }
        }
        return true;
    }
    /**
     * 获取服务器上的图片尺寸
     */
    public static int[] getImgWH(String urls) throws Exception {

        URL url = new URL(urls);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.connect();
        InputStream is = conn.getInputStream();
        Bitmap image = BitmapFactory.decodeStream(is);

        int srcWidth = image.getWidth();      // 源图宽度
        int srcHeight = image.getHeight();    // 源图高度
        int[] imgSize = new int[2];
        imgSize[0] = srcWidth;
        imgSize[1] = srcHeight;

        //释放资源
        image.recycle();
        is.close();
        conn.disconnect();

        return imgSize;

    }

    /**
     * 设置语言
     * @param num
     */
    public static void setLanguage(int num){
        int selectedLanguage = 0;
        if(num == 1){
            selectedLanguage = LanguageType.LANGUAGE_TRADITIONAL_CHINESE;
        }else if(num == 2){
            selectedLanguage = LanguageType.LANGUAGE_EN;
        }else if(num == 3){
            selectedLanguage = LanguageType.LANGUAGE_FOLLOW_SYSTEM;
        }else if(num == 0){
            selectedLanguage = LanguageType.LANGUAGE_CHINESE_SIMPLIFIED;
        }
        MultiLanguageUtil.getInstance().updateLanguage(selectedLanguage);
    }
    static ClipboardManager mClipboard;
    /**
     * 复制内容
     */
    public static void copyFromEditText(String copy) {
        // Gets a handle to the clipboard service.
        if (null == mClipboard) {
            mClipboard = (ClipboardManager) AppUtils.getContext().getSystemService(Context.CLIPBOARD_SERVICE);
        }
        // Creates a new text clip to put on the clipboard
        ClipData clip = ClipData.newPlainText("simple text copy",
                copy);
        // Set the clipboard's primary clip.
        mClipboard.setPrimaryClip(clip);
        ToastUtil.show(AppUtils.getContext().getString(R.string.link_copied));
    }

    /**
     * 截取大括号{}中的内容
     */
//    public static Pattern pattern1 = Pattern.compile("(?<=\\{)[^\\}]+");
//    public static Pattern pattern1 = Pattern.compile("\\{.*?\\}}");
    public static Pattern pattern1 = Pattern.compile("(?<=\\{)(.+?)(?=\\})");
    public static String bigParantheses(String context){
//        Matcher m = pattern1.matcher(context);
//        while (m.find()) {
//            System.out.println("Found value: " + m.group() );
//        }
//        String group = m.group();
        String quStr=context.substring(context.indexOf("{")+1,context.indexOf("}"));
//        return Integer.parseInt(quStr);
        return quStr;
    }
    /**
     * 判断str1中包含str2的个数
     * @param str1
     * @param str2
     * @return counter
     */
    public static int countStr(String str1, String str2) {
        if (str1.indexOf(str2) == -1) {
            return 0;
        } else if (str1.indexOf(str2) != -1) {
            counter++;
            countStr(str1.substring(str1.indexOf(str2) +
                    str2.length()), str2);
            return counter;
        }
        return 0;
    }
    /**
     * 将时间转换成时间戳
     * 设置即构、阿里云需要的时间戳(秒)
     * @return counter
     */
    public static String dataToStamp() {
        long time = System.currentTimeMillis();
        time += 30*1000*60;//在当前系统时间加30分钟,有效时间30分钟
        String res = "";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date data = simpleDateFormat.parse(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time));
            long ts = data.getTime();//得出的是毫秒,阿里云需要的是秒,所以除以1000
            ts = ts/1000;
            res = String.valueOf(ts);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return res;
    }
}

a.设置一个TextView多种颜色,使用Html.fromHtm封装设置颜色

 tv_unregitered_username.setText(Html.fromHtml(getString(R.string.unregistered_password_tip1)+StringUtil.setStrRed(getString(R.string.unregistered_password_tip2))));

3.BigDecimalUtils处理科学计算法方式,保留指定小数

import java.math.BigDecimal;
import java.text.DecimalFormat;

public class BigDecimalUtils {

    public static String getString(double d) {
        BigDecimal bigDecimal  = new BigDecimal(String.valueOf(d));
        return bigDecimal.toPlainString();
    }

    public static String getString_0(double d) {
        BigDecimal bigDecimal  = new BigDecimal(new DecimalFormat("0").format(d));
        return bigDecimal.toPlainString();
    }

    public static String getString_2(double d) {
        BigDecimal bigDecimal  = new BigDecimal(new DecimalFormat("0.00").format(d));
        return bigDecimal.toPlainString();
    }

    public static boolean isShow(String lock){
        return Double.parseDouble(lock) > 0;
    }
    /**
     * 保留4位小数
     * @param d
     * @return
     */
    public static String getString_4(double d) {
        BigDecimal bigDecimal  = new BigDecimal(new DecimalFormat("0.0000").format(d));

        return bigDecimal.toPlainString();
    }
}
edt_number.setText(BigDecimalUtils.getString(maxCanUse).toString())

3.BigDecimalUtils 保留小数位数、小于万默认显示 大于万以1.7万方式显示最大是9999.9万等

package com.duoge.weeboos.siji.utils;

import com.google.zxing.common.StringUtils;

import java.math.BigDecimal;
import java.text.DecimalFormat;

public class BigDecimalUtils {

    public static String getString(double d) {
        BigDecimal bigDecimal  = new BigDecimal(String.valueOf(d));
        return bigDecimal.toPlainString();
    }

    public static String getString_0(double d) {
        BigDecimal bigDecimal  = new BigDecimal(new DecimalFormat("0").format(d));
        return bigDecimal.toPlainString();
    }

    public static String getString_2(double d) {
        BigDecimal bigDecimal  = new BigDecimal(new DecimalFormat("0.00").format(d));
        return bigDecimal.toPlainString();
    }

    public static boolean isShow(String lock){
        return Double.parseDouble(lock) > 0;
    }
    /**
     * 保留4位小数
     * @param d
     * @return
     */
    public static String getString_4(double d) {
        BigDecimal bigDecimal  = new BigDecimal(new DecimalFormat("0.0000").format(d));

        return bigDecimal.toPlainString();
    }
    /**
     * <pre>
     * 数字格式化显示
     * 小于万默认显示 大于万以1.7万方式显示最大是9999.9万
     * 大于亿以1.1亿方式显示最大没有限制都是亿单位
     * make by dongxh 2017年12月28日上午10:05:22
     * </pre>
     * @param num
     *            格式化的数字
     * @param kBool
     *            是否格式化千,为true,并且num大于999就显示999+,小于等于999就正常显示
     * @return
     */
    public static String formatNum(String num, Boolean kBool) {
        StringBuffer sb = new StringBuffer();
        if (!isNumeric(num))
            return "0";
        if (kBool == null)
            kBool = false;

        BigDecimal b0 = new BigDecimal("1000");
        BigDecimal b1 = new BigDecimal("10000");
        BigDecimal b2 = new BigDecimal("100000000");
        BigDecimal b3 = new BigDecimal(num);

        String formatNumStr = "";
        String nuit = "";

        // 以千为单位处理
        if (kBool) {
            if (b3.compareTo(b0) == 0 || b3.compareTo(b0) == 1) {
                return "999+";
            }
            return num;
        }

        // 以万为单位处理
        if (b3.compareTo(b1) == -1) {
            sb.append(b3.toString());
        } else if ((b3.compareTo(b1) == 0 && b3.compareTo(b1) == 1)
                || b3.compareTo(b2) == -1) {
            formatNumStr = b3.divide(b1).toString();
            nuit = "万";
        } else if (b3.compareTo(b2) == 0 || b3.compareTo(b2) == 1) {
            formatNumStr = b3.divide(b2).toString();
            nuit = "亿";
        }
        if (!"".equals(formatNumStr)) {
            int i = formatNumStr.indexOf(".");
            if (i == -1) {
                sb.append(formatNumStr).append(nuit);
            } else {
                i = i + 1;
                String v = formatNumStr.substring(i, i + 1);
                if (!v.equals("0")) {
                    sb.append(formatNumStr.substring(0, i + 1)).append(nuit);
                } else {
                    sb.append(formatNumStr.substring(0, i - 1)).append(nuit);
                }
            }
        }
        if (sb.length() == 0)
            return "0";
        return sb.toString();
    }
//     StringUtils.isNumeric(null)   = false
//             StringUtils.isNumeric("")     = false
//             StringUtils.isNumeric("  ")   = false
//             StringUtils.isNumeric("123")  = true
//             StringUtils.isNumeric("१२३")  = true
//             StringUtils.isNumeric("12 3") = false
//             StringUtils.isNumeric("ab2c") = false
//             StringUtils.isNumeric("12-3") = false
//             StringUtils.isNumeric("12.3") = false
//             StringUtils.isNumeric("-123") = false
//             StringUtils.isNumeric("+123") = false
//
//    看其源码就知道,它这里仅仅对每个字符做了数字判断
    public static boolean isNumeric(String str) {
        if (str == null) {
            return false;
        } else {
            int sz = str.length();

            for(int i = 0; i < sz; ++i) {
                if (!Character.isDigit(str.charAt(i))) {
                    return false;
                }
            }

            return true;
        }
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值