工具类

被刻印的时光 ゝ 提交于 2019-11-27 08:28:25
public class CommonUtil implements InputFilter,BaseUtil{    //////////////////////////////////////////////////通用级工具//////////////////////////////////////////////////    /**     * 颜色类型常量     */    private static final int STYLE_COLOR_1 = 1;    private static final int STYLE_COLOR_2 = 2;    private static final int STYLE_COLOR_3 = 3;    /**     * null常量     */    private static final String COMMON_NULL = "null";    private Pattern mPattern;    public CommonUtil() {        String pattern = "[1-9]{1}\\d{0,8}";        this.mPattern = Pattern.compile(pattern);    }    /**     * 将数据字典list转为Popup可使用的list(判空了)     *     * @param dataList List<DataDictionaryResponse.ListBean.ItemsListBean>     * @return List<MessageListBean.MessageItem>     */    public static List<MessageListBean.MessageItem> formatToPopupList(List<DataDictionaryResponse            .ListBean.ItemsListBean> dataList) {        List<MessageListBean.MessageItem> result = new ArrayList<>();        if (dataList == null) {            return result;        }        for (DataDictionaryResponse.ListBean.ItemsListBean bean : dataList) {            MessageListBean.MessageItem item = new MessageListBean.MessageItem();            item.setId(bean.getDicKey());            item.setTextContent(bean.getDicVal());            result.add(item);        }        return result;    }    public static String convertEmpty(String str) {        return str == null ? "" : str;    }    /**     * jsonStr转bean     *     * @param str String     * @return T 如果str不是json就返回null     */    public static <T> T jsonToBean(String str, Class<T> classOfT) {        try {            return new Gson().fromJson(str, classOfT);        } catch (Exception e) {            return null;        }    }    /**     * jsonStr转list     *     * @param str String     * @return List<T> 如果str不是json就返回null     */    public static <T> List<T> jsonToList(String str) {        try {            return new Gson().fromJson(str, new TypeToken<List<T>>() {            }.getType());        } catch (Exception e) {            return null;        }    }    /**     * list转jsonStr     *     * @param o Object     * @return String     */    public static String beanToJson(Object o) {        return new Gson().toJson(o);    }    /**     * 资料选择器类型list转FileBean类型list     *     * @param list List<DatumBean>     * @param type 1: 个人 2: 公司     * @return List<FileBean>     */    public static List<FileBean> changeDatumBeanToFileBean(List<DatumBean> list, String type) {        List<FileBean> fileBeans = new ArrayList<>();        if (ListUtil.isEmpty(list)) {            return fileBeans;        } else {            for (int i = 0; i < list.size(); i++) {                FileBean fileBean = new FileBean();                fileBean.setId(list.get(i).getId());                fileBean.setFileId(list.get(i).getFileId());                fileBean.setFileResId(list.get(i).getFileResId());                fileBean.setFileName(list.get(i).getFileName());                fileBean.setFilePath(list.get(i).getFilePath());                fileBean.setFileSize(String.valueOf(list.get(i).getFileSize()));                fileBean.setFileType(list.get(i).getFileType());                fileBean.setFileTime(list.get(i).getFileDuration());                if (!TextUtils.isEmpty(list.get(i).getCoverId())) {                    if (list.get(i).getCoverId().startsWith("http")) {                        String substring = list.get(i).getCoverId().substring(list.get(i).getCoverId().indexOf("id="));                        String str = substring.replace("id=", "");                        fileBean.setThumbId(str);                    }                }                //type类型 1: 个人 2: 公司                fileBean.setFileSuffix(type);                fileBeans.add(fileBean);            }            return fileBeans;        }    }    /**     * FileBean类型list转资料选择器类型list     *     * @param list List<FileBean>     * @param type 1: 个人 2: 公司     * @return List<DatumBean>     */    public static List<DatumBean> changeFileBeanToDatumBean(List<FileBean> list) {        List<DatumBean> datumBeanArrayList = new ArrayList<>();        if (ListUtil.isEmpty(list)) {            return datumBeanArrayList;        } else {            for (int i = 0; i < list.size(); i++) {                DatumBean datumBean = new DatumBean();                datumBean.setId(list.get(i).getId());                datumBean.setFileId(list.get(i).getFileId());                datumBean.setFileResId(list.get(i).getFileResId());                datumBean.setFileName(list.get(i).getFileName());                datumBean.setFilePath(list.get(i).getFilePath());                datumBean.setFileSize(Integer.parseInt(list.get(i).getFileSize()));                datumBean.setFileType(list.get(i).getFileType());                datumBean.setFileDuration(list.get(i).getFileTime());                //待修改-不知道对不对                if (!TextUtils.isEmpty(list.get(i).getThumbId())) {                    datumBean.setCoverId(list.get(i).getThumbId());                }                datumBeanArrayList.add(datumBean);            }            return datumBeanArrayList;        }    }    /**     * 格式化数字,保留两位小数     * #:占位是0舍去  0:补位不舍去0     *     * @param num 输入的数字     * @return 保留2位小数的字符串 若空值返回""     */    public static String formatDecimalNum(String num) {        if (!TextUtils.isEmpty(num)) {            try {                DecimalFormat decimalFormat = new DecimalFormat("##0.00");                BigDecimal newMoney = new BigDecimal(num)                        .setScale(2, BigDecimal.ROUND_HALF_UP);                return decimalFormat.format(newMoney);            } catch (Exception e) {                e.printStackTrace();                return num;            }        } else {            return "";        }    }    /**     * 格式化数字,带千分符,保留两位小数     * #:占位是0舍去  0:补位不舍去0     *     * @param num 输入的数字(9位 + 2位小数 = 共11位)     * @return 带千分符, 保留2位小数的字符串 若空值返回""     */    public static String formatMoney(String num) {        if (!TextUtils.isEmpty(num)) {            num = num.replace(",", "");            DecimalFormat decimalFormat = new DecimalFormat("##,###,###,##0.00");            BigDecimal newMoney = new BigDecimal(num)                    .setScale(2, BigDecimal.ROUND_HALF_UP);            return decimalFormat.format(newMoney);        } else {            return "";        }    }    public static String unFormatMoney(String str) {        if (TextUtils.isEmpty(str)) {            return "";        }        return str.replace(",", "");    }    /**     * 格式化数字(取整)     *     * @param s String     * @return String     */    public String formatIntegerNum(String s) {        if (!TextUtils.isEmpty(s) && !COMMON_NULL.equals(s)) {            int floor = (int) Math.floor(Double.parseDouble(s));            return String.valueOf(floor);        } else {            return "0";        }    }    /**     * 格式化时间String(中国)     *     * @param strTime    要转换的string类型的时间     * @param formatType 转换的格式 例 yyyy-MM-dd HH:mm:ss (年-月-日 时:分:秒)     * @return String类型的时间     */    public static String formatDateTime(String strTime, String formatType) {        SimpleDateFormat mFormat = new SimpleDateFormat(formatType, Locale.CHINA);        String dateTime = "";        try {            Date date = mFormat.parse(strTime);            dateTime = mFormat.format(date);        } catch (ParseException e) {            e.printStackTrace();        }        return dateTime;    }    /**     * 格式化时间     *     * @param strTime    时间字符串     * @param formatType 转换的格式: yyyy-MM-dd HH:mm     * @return String     */    public static String stringToString(String strTime, String formatType) {        if (android.text.TextUtils.isEmpty(strTime)) {            return "";        }        @SuppressLint("SimpleDateFormat")        SimpleDateFormat sdf = new SimpleDateFormat(formatType);        String dateTime = "";        try {            Date date = sdf.parse(strTime);            dateTime = sdf.format(date);        } catch (ParseException e) {            e.printStackTrace();        }        return dateTime;    }    /**     * 格式化数字     *     * @param num int     * @return String     */    public static String formatSingleDigit(int num) {        DecimalFormat df = new DecimalFormat("00");        return df.format(num);    }    /**     * 格式化手机号 130 0000 0000     *     * @param num 输入的数字     * @return 若空值返回""     */    public static String formatPhone(String num) {        if (TextUtils.isEmpty(num)) {            return "";        }        if (!MatchUtil.matchAllPhone(num)) {            return num;        }        if (num.contains("-")) {            return num;        }        return num.substring(0, 3) + " " + num.substring(3, 7) + " " + num.substring(7, 11);    }    /**     * 将时间转换为long格式     *     * @param strTime    要转换的String类型的时间,与formatType的时间格式必须相同     * @param formatType 时间格式     * @return long     * @throws ParseException ParseException     */    public static long stringToLong(String strTime, String formatType)            throws ParseException {        //String类型转成date类型        Date date = stringToDate(strTime, formatType);        if (date == null) {            return 0;        } else {            //date类型转成long类型            return dateToLong(date);        }    }    /**     * 获取请假时间     *     * @param begin 开始时间     * @param end   结束时间     * @return Double(小时数)     * @author DAKANG     * Create At : 2018-12-22 17:15     */    public static String getLeaveTime(long begin, long end) {        Date dateBegin = new Date(begin);        Date dateEnd = new Date(end);        @SuppressLint("SimpleDateFormat")        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");        simpleDateFormat.format(dateBegin);        simpleDateFormat.format(dateEnd);        Calendar calendar = Calendar.getInstance();        calendar.setTime(dateBegin);        Long endt = dateEnd.getTime();        Double time = 0.0;        while (calendar.getTimeInMillis() < endt) {            if (calendar.get(Calendar.DAY_OF_WEEK) == 1) {                calendar.add(Calendar.DAY_OF_MONTH, 1);                calendar.set(Calendar.MINUTE, 0);                calendar.set(Calendar.HOUR_OF_DAY, 8);                calendar.set(Calendar.SECOND, 0);                continue;            }            int hour = calendar.get(Calendar.HOUR_OF_DAY);            if (hour < 8) {                calendar.set(Calendar.MINUTE, 0);                calendar.set(Calendar.HOUR_OF_DAY, 8);                calendar.set(Calendar.SECOND, 0);                if (calendar.getTimeInMillis() > endt) {                    break;                }            } else if (hour >= 8 && hour < 12) {                long times = calendar.getTimeInMillis();                calendar.set(Calendar.MINUTE, 0);                calendar.set(Calendar.HOUR_OF_DAY, 12);                calendar.set(Calendar.SECOND, 0);                if (calendar.getTimeInMillis() > endt) {                    time += (endt - times);                    break;                }                time += (calendar.getTimeInMillis() - times);            } else if (hour >= 12 && hour < 13) {                calendar.set(Calendar.MINUTE, 0);                calendar.set(Calendar.HOUR_OF_DAY, 13);                calendar.set(Calendar.SECOND, 0);                if (calendar.getTimeInMillis() > endt) {                    break;                }            } else if (hour >= 13 && hour < 18) {                long times = calendar.getTimeInMillis();                calendar.set(Calendar.MINUTE, 0);                calendar.set(Calendar.HOUR_OF_DAY, 18);                calendar.set(Calendar.SECOND, 0);                if (calendar.getTimeInMillis() > endt) {                    time += (endt - times);                    break;                }                time += (calendar.getTimeInMillis() - times);            } else if (hour >= 18) {                calendar.add(Calendar.DAY_OF_MONTH, 1);                calendar.set(Calendar.MINUTE, 0);                calendar.set(Calendar.HOUR_OF_DAY, 8);                calendar.set(Calendar.SECOND, 0);                if (calendar.getTimeInMillis() > endt) {                    break;                }            }        }        double tempTime = time / (double) 3600000;        BigDecimal bigDecimal = new BigDecimal(tempTime);        bigDecimal = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);        return String.valueOf(bigDecimal.toString());    }    /**     * 设置TextView展示时,大于一行文字靠左显示,否则靠右显示     *     * @param textView TextView     */    public static void showTextView(TextView textView) {        //使用post,绘制完成后调用getLineCount(),不然返回值一直是0        textView.post(() -> {            //判断TextView的行数,大于一行靠左显示,否则靠右显示            if (textView.getLineCount() > 1) {                textView.setGravity(Gravity.START);            } else {                textView.setGravity(Gravity.END);            }        });    }    /**     * 设置状态栏样式     *     * @param context    上下文     * @param colorStyle 样式: 1-黑橘底白字(橘色导航) 2-黑底白字(黑色导航) 3-灰底白字(白色导航)     */    public static void setStatusBarColor(Context context, int colorStyle) {        int color;        switch (colorStyle) {            case STYLE_COLOR_1:                color = Color.parseColor("#CC9030");                break;            case STYLE_COLOR_2:                color = Color.parseColor("#353535");                break;            case STYLE_COLOR_3:                color = Color.parseColor("#CCCCCC");                break;            default:                throw new IllegalArgumentException("You must select a correct color style for " +                        "CommonToolbar.");        }        StatusBarUtil.setColor((Activity) context, color, DEFAULT_STATUS_BAR_ALPHA);    }    private static final Pattern PATTERN = Pattern.compile("(^[1-9](\\d{0,4})?(\\.\\d{1,2})?$)|(^(0){1}$)|(^\\d\\.\\d{1,2}?$)");    /**     * EditText监听(最大可输入7位(包含小数点后两位))     *     * @param num num     */    public static boolean macthMoney7(String num) {        Matcher matcher = PATTERN.matcher(num);        return matcher.matches();    }    /**     * EditText监听(使其无法空格保存)     *     * @param editText EditText     */    public static void dialogAddListener(EditText editText) {        editText.addTextChangedListener(new TextWatcher() {            @Override            public void beforeTextChanged(CharSequence s, int start, int count, int after) {            }            @Override            public void onTextChanged(CharSequence s, int start, int before, int count) {            }            @Override            public void afterTextChanged(Editable s) {                if (!"".equals(s.toString()) && com.alibaba.android.arouter.utils.TextUtils.isEmpty(s.toString().trim())) {                    editText.setText("");                }            }        });    }    /**     * 无法输入中文     *     * @param editText EditText     */    public static void dialogAddWordListener(EditText editText) {        editText.addTextChangedListener(new TextWatcher() {            @Override            public void beforeTextChanged(CharSequence s, int start, int count, int after) {            }            @Override            public void onTextChanged(CharSequence s, int start, int before, int count) {            }            @Override            public void afterTextChanged(Editable s) {                if (s.length() > 0) {                    for (int i = 0; i < s.length(); i++) {                        char c = s.charAt(i);                        if (c >= 0x4e00 && c <= 0X9fff) {                            // 根据字节码判断                            // 如果是中文,则清除输入的字符,否则保留                            s.delete(i, i + 1);                        }                    }                }            }        });    }    //////////////////////////////////////////////////模块级工具//////////////////////////////////////////////////    public static void setChartStyle(Context mContext, LineChart mChart) {        LineChartBasicHelper helper = new LineChartBasicHelper<Entry>(mChart, mContext);//        mChart.setDragEnabled(false);//        // 设置背景色//        mChart.setBackgroundColor(Color.WHITE);//        // 允许触摸//        mChart.setTouchEnabled(true);//        // 设置禁止缩放//        mChart.setScaleEnabled(false);        // 设置禁止双击屏幕缩放//        mChart.setDoubleTapToZoomEnabled(false);//        mChart.getDescription().setEnabled(false);        mChart.getLegend().setEnabled(false);        mChart.setNoDataText("暂无数据");        XAxis xAxis = mChart.getXAxis();//        xAxis.setAvoidFirstLastClipping(true);////        xAxis.setLabelCount(7);//        xAxis.setTextColor(ContextCompat.getColor(mContext, R.color.c125));//        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//        xAxis.setDrawGridLines(false);        YAxis yAxis = mChart.getAxisLeft();        yAxis.setLabelCount(6, true);//        yAxis.//        yAxis.setStartAtZero(false);//        yAxis.setDrawGridLines(true);//        yAxis.setGridLineWidth(0.5f);//        yAxis.setGridColor(ContextCompat.getColor(mContext, R.color.c127));//        yAxis.setTextColor(ContextCompat.getColor(mContext, R.color.c125));//        mChart.getAxisRight().setEnabled(false);    }    public static void setChartData(Context mContext, LineChart chart, List<String> mXAxisList, ArrayList<Entry> values1) {//        ArrayList<Entry> values1 = new ArrayList<>();//        List<String> mXAxisList = new ArrayList<>();////        for (int i = 0; i < count; i++) {//            float val = (float) (Math.random() * (range / 2f)) + 50;//            values1.add(new Entry(i, val));//            mXAxisList.add("03-" + i);//        }        LineDataSet set1;        chart.clear();        if (chart.getData() != null &&                chart.getData().getDataSetCount() > 0) {            set1 = (LineDataSet) chart.getData().getDataSetByIndex(0);            set1.setValues(values1);//            set1.notifyDataSetChanged();//            chart.getAxisLeft().setAxisMinimum(chart.getData().getYMin());            float ymin = chart.getData().getYMin(YAxis.AxisDependency.LEFT);            if (ymin < 0) {                if (chart.getData().getYMin() < 0) {                    chart.getAxisLeft().setAxisMinimum(ymin);                } else {                    ymin = 0;                    chart.getAxisLeft().setAxisMinimum(ymin);                }            } else {                chart.getAxisLeft().setAxisMinimum(ymin);            }            float ymax = chart.getData().getYMax(YAxis.AxisDependency.LEFT);            if (ymax == ymin) {                chart.getAxisLeft().setAxisMaximum(((int) ((ymax - ymin) / 5)) * 5 + 5 + ymin);            } else if ((ymax - ymin) % 5 == 0) {                chart.getAxisLeft().setAxisMaximum(ymax);            } else {                chart.getAxisLeft().setAxisMaximum(((int) ((ymax - ymin) / 5)) * 5 + 5 + ymin);            }            chart.getData().notifyDataChanged();            chart.notifyDataSetChanged();        } else {            set1 = new LineDataSet(values1, "DataSet 1");            set1.setAxisDependency(YAxis.AxisDependency.LEFT);            set1.setColor(ContextCompat.getColor(mContext, R.color.c201));            set1.setCircleColor(ContextCompat.getColor(mContext, R.color.c201));            set1.setLineWidth(1);            set1.setCircleRadius(2);            set1.setHighLightColor(ContextCompat.getColor(mContext, R.color.c201));            set1.setDrawCircleHole(false);            LineData data = new LineData(set1);            data.setDrawValues(false);//            mChart.getAxisLeft().setAxisMinimum(0);            float ymin = data.getYMin(YAxis.AxisDependency.LEFT);            if (ymin < 0) {                if (data.getYMin() < 0) {                    chart.getAxisLeft().setAxisMinimum(ymin);                } else {                    ymin = 0;                    chart.getAxisLeft().setAxisMinimum(ymin);                }            } else {                chart.getAxisLeft().setAxisMinimum(ymin);            }            float ymax = data.getYMax(YAxis.AxisDependency.LEFT);            if (ymax == ymin) {                chart.getAxisLeft().setAxisMaximum(((int) ((ymax - ymin) / 5)) * 5 + 5 + ymin);            } else if ((ymax - ymin) % 5 == 0) {                chart.getAxisLeft().setAxisMaximum(ymax);            } else {                chart.getAxisLeft().setAxisMaximum(((int) ((ymax - ymin) / 5)) * 5 + 5 + ymin);            }            chart.getXAxis().setValueFormatter(new AxisValueFormatter(mXAxisList));            chart.setData(data);            chart.invalidate();        }    }    public static Double getString2Double(String str) {        try {            return Double.parseDouble(str);        } catch (Exception var2) {            var2.printStackTrace();            return 0d;        }    }    public static Double getValByPercent(String str) {        if (TextUtils.isEmpty(str)) {            return 0d;        }        String val;        if (str.endsWith("%")) {            val = str.substring(0, str.length() - 1);        } else {            val = str;        }        return getString2Double(val) / 100;    }    public static String getPercentByString(String val) {        try {            DecimalFormat decimalFormat = new DecimalFormat("##0.##");            BigDecimal newMoney = new BigDecimal(val);            return decimalFormat.format(newMoney.multiply(new BigDecimal("100"))) + "%";        } catch (Exception e) {            e.printStackTrace();            return val;        }    }    @Override    public CharSequence filter(CharSequence source, int start, int end, Spanned destination, int destinationStart, int destinationEnd) {        if (end > start) {            // adding: filter            // build the resulting text            String destinationString = destination.toString();            String resultingTxt = destinationString.substring(0, destinationStart) + source.subSequence(start, end) + destinationString.substring(destinationEnd);            // return null to accept the input or empty to reject it            return resultingTxt.matches(this.mPattern.toString()) ? null : "";        }        // removing: always accept        return null;    }}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!