自己写的一些常用的方法,可以封装成一个类,记录下来
package com.todayhead.utils; import java.math.BigDecimal; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.text.TextUtils; import android.util.Log; import android.widget.EditText; /** * 1.判断是否联网 * 2.验证邮箱地址是否正确 * 3.判断身份证号码 * 4.获取保留的小数位数 * 5.根据日期获得星期 * 6.判断是正整数还是小数 * 7.验证账户 * 8.验证手机号码 * 9.电话号码验证 * 10.检测密码 * 11.判断网络连接 * 12.验证邮政编码 * 13.打电话 * 14.检验是否存在非法字符 * 15.EditText竖直方向是否可以滚动 * 16.获取当月的 天数 * 17.根据年 月 获取对应的月份 天数 * 18.根据日期 找到对应日期的 星期 * 19.设置时间格式 * 20.设置时间格式,转成成时间搓 * 21.传入时间搓输出时间类型 * 22.获取当前年月日 * 23.获取当前年月 */ public class MyUtil { /** 判断是否联网 */ public static boolean isNetWork(Context context) { boolean isNetWork = false; ConnectivityManager cwjManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = cwjManager.getActiveNetworkInfo(); if (info != null && info.isAvailable()) { isNetWork = true; } else { isNetWork = false; } return isNetWork; } /** * 验证邮箱地址是否正确 * @param email * @return */ public static boolean checkEmail(String email) { boolean flag = false; try { String check = "^([a-z0-9A-Z]+[_-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$"; Pattern regex = Pattern.compile(check); Matcher matcher = regex.matcher(email); flag = matcher.matches(); } catch (Exception e) { flag = false; } return flag; } /** * 判断身份证号码 * @param str * @return */ public static boolean checkPersonID(String str){ String isIDCard1="^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$";//判断15位身份证号码 String isIDCard2="^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X|x)$";//判断18位身份证号码 return str.matches(isIDCard1) || str.matches(isIDCard2); } /** * 获取保留的小数位数 * @param str * @return * String str="86.64466666"; * 86.64=86.64=86.64=86.64 */ public static String getBigDecimal(String str){ BigDecimal bd = new BigDecimal(Double.parseDouble(str)); System.out.println(bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()); System.out.println("================="); DecimalFormat df = new DecimalFormat("#.00"); System.out.println(df.format(Double.parseDouble(str))); System.out.println("================="); System.out.println(String.format("%.2f", Double.parseDouble(str))); System.out.println("================="); NumberFormat nf = NumberFormat.getNumberInstance(); nf.setMaximumFractionDigits(2); System.out.println(nf.format(Double.parseDouble(str))); return bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()+""; } /** * 根据日期获得星期 * @param date * @return */ public static String getWeekOfDate(Date date) { String[] weekDaysName = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" }; String[] weekDaysCode = { "0", "1", "2", "3", "4", "5", "6" }; Calendar calendar = Calendar.getInstance(); calendar.setTime(date); int intWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1; return weekDaysName[intWeek]; } /** * 判断是正整数还是小数 * @param str * @return */ public static boolean isNum(String str){ String num = "^([0-9]*)([.]?)([0-9]+)"; String num1 = "^[-+]?(([0-9]+)([.]([0-9]+))?|([.]([0-9]+))?)$"; return str.matches(num); } /** * 验证账户 * @param account * @return */ public static boolean checkAccount(String account) { boolean flag = false; try { String check = "^[a-zA-Z0-9@.]{1,24}+$"; Pattern p = Pattern.compile(check); Matcher m = p.matcher(account); flag = m.matches(); } catch (Exception e) { flag = false; } return flag; } /** * 验证手机号码 * @param mobiles * @return */ public static boolean isMobileNO(String mobiles) { boolean flag = false; try { Pattern p = Pattern.compile("^(1)\\d{10}$"); Matcher m = p.matcher(mobiles); flag = m.matches(); } catch (Exception e) { flag = false; } return flag; } /** * 电话号码验证 * * @param str * @return 验证通过返回true */ public static boolean isPhone(String str) { Pattern p1 = null,p2 = null; Matcher m = null; boolean b = false; p1 = Pattern.compile("^[0][1-9]{2,3}-[0-9]{5,10}$"); // 验证带区号的 p2 = Pattern.compile("^[1-9]{1}[0-9]{5,8}$"); // 验证没有区号的 if(str.length() >9) { m = p1.matcher(str); b = m.matches(); }else{ m = p2.matcher(str); b = m.matches(); } return b; } /** * 检测密码 * * @param pwd * @return */ public static boolean checkPwd(String pwd) { boolean flag = false; try { String check = "^[a-zA-Z0-9]{6,20}+$"; Pattern regex = Pattern.compile(check); Matcher matcher = regex.matcher(pwd); flag = matcher.matches(); } catch (Exception e) { flag = false; } return flag; } /** * 判断网络连接 * @param context * @return */ public static boolean isNetworkAvailable(Context context) { ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); if (cm == null) { } else { NetworkInfo[] info = cm.getAllNetworkInfo(); if (info != null) { for (int i = 0; i < info.length; i++) { if (info[i].isAvailable()&&info[i].getState() == NetworkInfo.State.CONNECTED) { return true; } } } } return false; } //验证邮政编码 public static boolean checkPost(String post){ if(post.matches("[1-9]\\d{5}(?!\\d)")){ return true; }else{ return false; } } /** * 打电话 * @param context * @param tel */ public static void callPhone(Context context, String tel) { if (TextUtils.isEmpty(tel)) { tel = ""; } Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + tel)); context.startActivity(intent); } /** * 检验是否存在非法字符 */ public static boolean IllegalChar(String args) { if(args.matches("[a-zA-Z0-9_\u4e00-\u9fa5]*")){ //不是非法字符 return false; } return true; } /** * EditText竖直方向是否可以滚动 * @param editText 需要判断的EditText * @return true:可以滚动 false:不可以滚动 */ public static boolean canVerticalScroll(EditText editText) { //滚动的距离 int scrollY = editText.getScrollY(); //控件内容的总高度 int scrollRange = editText.getLayout().getHeight(); //控件实际显示的高度 int scrollExtent = editText.getHeight() - editText.getCompoundPaddingTop() -editText.getCompoundPaddingBottom(); //控件内容总高度与实际显示高度的差值 int scrollDifference = scrollRange - scrollExtent; if(scrollDifference == 0) { return false; } return (scrollY > 0) || (scrollY < scrollDifference - 1); } /** * 获取当月的 天数 * */ public static int getCurrentMonthDay() { Calendar a = Calendar.getInstance(); a.set(Calendar.DATE, 1); a.roll(Calendar.DATE, -1); int maxDate = a.get(Calendar.DATE); return maxDate; } /** * 根据年 月 获取对应的月份 天数 * */ public static int getDaysByYearMonth(int year, int month) { Calendar a = Calendar.getInstance(); a.set(Calendar.YEAR, year); a.set(Calendar.MONTH, month - 1); a.set(Calendar.DATE, 1); a.roll(Calendar.DATE, -1); int maxDate = a.get(Calendar.DATE); return maxDate; } /** * 根据日期 找到对应日期的 星期 */ public static String getDayOfWeekByDate(String date) { String dayOfweek = "-1"; try { SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd"); Date myDate = myFormatter.parse(date); SimpleDateFormat formatter = new SimpleDateFormat("E"); String str = formatter.format(myDate); dayOfweek = str; } catch (Exception e) { System.out.println("错误!"); } return dayOfweek; } /** *设置时间格式 */ public static String getDateType(String date) { String retu=null; try { SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd"); Date myDate = myFormatter.parse(date); retu=myFormatter.format(myDate); return retu; } catch (Exception e) { System.out.println("错误!"); } return retu; } /** *设置时间格式 */ public static String getDateType(String date,String type) { String retu=null; try { SimpleDateFormat myFormatter = new SimpleDateFormat(type); Date myDate = myFormatter.parse(date); retu=myFormatter.format(myDate); return retu; } catch (Exception e) { System.out.println("错误!"); } return retu; } /** *设置时间格式,转成成时间搓 */ public static Long getDateTime(String date,String type) { Long retu=null; try { SimpleDateFormat myFormatter = new SimpleDateFormat(type); Date myDate = myFormatter.parse(date); retu=myDate.getTime(); return retu; } catch (Exception e) { System.out.println("错误!"); } return retu; } /** * 传入时间搓输出时间类型 * 调用此方法输入所要转换的时间戳输入例如(1402733340)输出("2014年06月14日16时09分") * @param time * @param type * @return */ public static String SetTimeType(String time,String type){ String retu=null; String date2=null; try { Log.i("type", type); if(type.substring(0, 2).equals("hh")){ date2= new SimpleDateFormat("HH:mm").format(new Date(Long.parseLong(time))); }else{ date2= new SimpleDateFormat(type).format(new Date(Long.parseLong(time))); } Date date=new Date(Long.valueOf(time)); SimpleDateFormat myFormatter = new SimpleDateFormat(type); retu=myFormatter.format(date); Log.i("retu", retu); return date2; } catch (Exception e) { System.out.println("错误!"); } return retu; } /* * 获取当前年月日 */ public static String getCurDate(){ Calendar c=Calendar.getInstance(Locale.CHINA); int year=c.get(Calendar.YEAR); int month=c.get(Calendar.MONTH); int day=c.get(Calendar.DAY_OF_MONTH); return year+"-"+(month+1)+"-"+day; } /* * 获取当前年月 * 2016年9月 */ public static String getCurYearMonth(){ Calendar c=Calendar.getInstance(Locale.CHINA); int year=c.get(Calendar.YEAR); int month=c.get(Calendar.MONTH); int day=c.get(Calendar.DAY_OF_MONTH); return year+"年"+(month+1)+"月"; } /* * 获取当前年月 * 2016-9 */ public static String getCurYearMonthadd(){ Calendar c=Calendar.getInstance(Locale.CHINA); int year=c.get(Calendar.YEAR); int month=c.get(Calendar.MONTH); int day=c.get(Calendar.DAY_OF_MONTH); return year+"-"+(month+1); } }