Android 开发实用方法大全
1.格式化价格,这个经常在计算费用精度的时候用到
- /**
- * 格式化价格
- *
- * @param argStr 传入价格字符串
- * @return
- */
- public static String getFloatDotStr(String argStr) {
- float arg = Float.valueOf(argStr);
- DecimalFormat fnum = new DecimalFormat("##0.00");
- return fnum.format(arg);
- }
2.获取App的版本号Version
- // 得到versionCode
- public static int getVerCode(Context context) {
- int verCode = 0;
- try {
- verCode = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
- } catch (NameNotFoundException e) {
- e.printStackTrace();
- }
- return verCode;
- }
3.获取手机屏幕宽高:
- /**
- * 屏幕宽高
- *
- * @param context
- * @return 0:width,1:height
- */
- public static int[] ScreenSize(Context context) {
- DisplayMetrics metrics = new DisplayMetrics();
- ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(metrics);
- return new int[] { metrics.widthPixels, metrics.heightPixels };
- }
4.判断SD卡是否存在:
- /**
- * 判断sd卡是否存在
- *
- * @author
- * @return
- */
- public static boolean judgeSDCard() {
- String status = Environment.getExternalStorageState();
- return status.equals(Environment.MEDIA_MOUNTED);
- }
5.验证是否中文:
- /***
- * 验证是否中文
- *
- * @param
- * @return
- */
- public static boolean validName(String name) {
- String pattern = "[\u4e00-\u9fa5]";
- if (isNull(name))
- return false;
- return name.matches(pattern);
- }
6.验证身份证号码:
- /**
- * 验证身份证号码
- *
- * @author
- * @param idCard
- * @return
- */
- public static boolean validateIdCard(String idCard) {
- if (isNull(idCard))
- return false;
- String pattern = "^[0-9]{17}[0-9|xX]{1}$";
- return idCard.matches(pattern);
- }
7.验证手机号码:
- /**
- * 验证手机号码
- *
- * @author
- * @param phone
- * @return
- */
- public static boolean validatePhone(String phone) {
- if (isNull(phone))
- return false;
- String pattern = "^1[3,4,5,6,8]\\d{9}$";
- return phone.matches(pattern);
- }
8.验证邮编:
- /**
- * 判断邮编
- *
- * @param
- * @return
- */
- public static boolean isZipNO(String zipString) {
- String str = "^[1-9][0-9]{5}$";
- return Pattern.compile(str).matcher(zipString).matches();
- }
9.验证银行卡号:
- /**
- * 验证银行卡号
- *
- * @param bankCard
- * 信用卡是16位,其他的是13-19位
- * @return
- */
- public static boolean validateBankCard(String bankCard) {
- if (isNull(bankCard))
- return false;
- String pattern = "^\\d{13,19}$";
- return bankCard.matches(pattern);
- }
10.验证邮箱:
- /**
- * 验证邮箱
- *
- * @author
- * @param email
- * @return
- */
- public static boolean validateEmail(String email) {
- if (isNull(email))
- return false;
- String pattern = "^([a-zA-Z0-9_\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$";
- return email.matches(pattern);
- }
11.将图片设置为圆角图片:
- /**
- * 设置圆角的图片
- *
- * @author
- * @param bitmap
- * 图片
- * @param pixels
- * 角度
- * @return
- */
- public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {
- try {
- if (bitmap != null) {
- Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
- Canvas canvas = new Canvas(output);
- final int color = 0xff424242;
- final Paint paint = new Paint();
- final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
- final RectF rectF = new RectF(rect);
- final float roundPx = pixels;
- paint.setAntiAlias(true);
- canvas.drawARGB(0, 0, 0, 0);
- paint.setColor(color);
- canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
- paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
- canvas.drawBitmap(bitmap, rect, rect, paint);
- return output;
- }
- } catch (Exception e) {
- }
- return bitmap;
- }
- /**
- * 将图片转换为圆形的
- *
- * @author
- * @param bitmap
- * @return
- */
- public static Bitmap toRoundBitmap(Bitmap bitmap) {
- if (bitmap != null) {
- bitmap = cutSquareBitmap(bitmap);
- return toRoundCorner(bitmap, bitmap.getWidth() / 2);
- }
- return bitmap;
- }
12.判断有无网络链接
- // 判断有无网络链接
- public static boolean checkNetworkInfo(Context mContext) {
- ConnectivityManager conMan = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
- State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
- State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
- if (mobile == State.CONNECTED || mobile == State.CONNECTING)
- return true;
- if (wifi == State.CONNECTED || wifi == State.CONNECTING)
- return true;
- return false;
- }
13.判断是否连接wifi
- /**
- * 判断是否连接wifi
- *
- * @param mContext
- * @return 返回true则有wifi
- */
- private static boolean isWifi(Context mContext) {
- ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
- NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
- if (activeNetInfo != null && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
- return true;
- }
- return false;
- }
14.获取SIM卡存在的状态
- /** 获取SIM卡存在的状态 */
- public static String getSIMCardExist(Context context) {
- manager = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
- String state = "";
- switch (manager.getSimState()) {
- case TelephonyManager.SIM_STATE_READY:
- state = "良好";
- break;
- case TelephonyManager.SIM_STATE_ABSENT:
- state = "无SIM卡";
- break;
- default:
- state = "SIM卡被锁定或未知状态";
- break;
- }
- return state;
- }
15. bitmap和base64类型互转
- // 把bitmap转换成base64
- public static String getBase64FromBitmap(Bitmap bitmap, int bitmapQuality) {
- ByteArrayOutputStream bStream = new ByteArrayOutputStream();
- bitmap.compress(CompressFormat.JPEG, bitmapQuality, bStream);
- byte[] bytes = bStream.toByteArray();
- return Base64.encode(bytes);
- }
- // 把base64转换成bitmap
- public static Bitmap getBitmapFromBase64(String string) {
- byte[] bitmapArray = null;
- try {
- bitmapArray = Base64.decode(string);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
- }
16. 把图片流转换成byte数组
- /**
- *
- * 方法说明 把图片流转换成byte数组
- *
- * @author
- * @param
- * @return
- */
- public static byte[] getByteFromStream(InputStream inStream) {
- byte[] data = new byte[1024];
- byte[] buffer = new byte[1024];
- int len = -1;
- ByteArrayOutputStream outStream = new ByteArrayOutputStream();
- try {
- while ((len = inStream.read(buffer)) != -1) {
- outStream.write(buffer, 0, len);
- }
- data = outStream.toByteArray();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- outStream.close();
- inStream.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return data;
- }
17.把字节数组转化成bitmap
- /**
- *
- * 把字节数组转化成bitmap
- *
- * @author
- * @param
- * @return
- */
- public static Bitmap getBitmapFromBytes(byte[] bytes, BitmapFactory.Options opts) {
- if (bytes != null)
- if (opts != null)
- return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opts);
- else
- return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
- return null;
- }
18.把Stream转换成String
- // 把Stream转换成String
- public static String convertStreamToString(InputStream is) {
- BufferedReader reader = new BufferedReader(new InputStreamReader(is));
- StringBuilder sb = new StringBuilder();
- String line = null;
- try {
- while ((line = reader.readLine()) != null) {
- sb.append(line + "/n");
- }
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- is.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return sb.toString();
- }
19.防止按钮连续点击
- /**
- * 防止按钮连续点击
- */
- private static long lastClickTime;
- public static boolean isFastDoubleClick() {
- long time = System.currentTimeMillis();
- long timeD = time - lastClickTime;
- if (0 < timeD && timeD < 500) {
- return true;
- }
- lastClickTime = time;
- return false;
- }
20.保存图片到SD卡
- /**
- * 保存图片
- *
- * @param photoBitmap
- * @param path 保存路径
- */
- public static void savePhotoToSDCard(Bitmap photoBitmap, String path) {
- File photoFile = new File(path);
- FileOutputStream fileOutputStream = null;
- try {
- fileOutputStream = new FileOutputStream(photoFile);
- if (photoBitmap != null) {
- if (photoBitmap.compress(Bitmap.CompressFormat.JPEG, 70, fileOutputStream)) {
- fileOutputStream.flush();
- }
- }
- } catch (FileNotFoundException e) {
- photoFile.delete();
- e.printStackTrace();
- } catch (IOException e) {
- photoFile.delete();
- e.printStackTrace();
- } finally {
- try {
- fileOutputStream.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
21.将字符串转化为二维码:
- private static int QR_WIDTH = 300;
- private static int QR_HEIGHT = 300;
- public static Bitmap createQRImage(String url) {
- try {
- // 判断URL合法性
- if (url == null || "".equals(url) || url.length() < 1) {
- return null;
- }
- Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
- hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
- // 图像数据转换,使用了矩阵转换
- BitMatrix bitMatrix = new QRCodeWriter().encode(url, BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT);
- int[] pixels = new int[QR_WIDTH * QR_HEIGHT];
- // 下面这里按照二维码的算法,逐个生成二维码的图片,
- // 两个for循环是图片横列扫描的结果
- for (int y = 0; y < QR_HEIGHT; y++) {
- for (int x = 0; x < QR_WIDTH; x++) {
- if (bitMatrix.get(x, y)) {
- pixels[y * QR_WIDTH + x] = 0xff000000;
- } else {
- pixels[y * QR_WIDTH + x] = 0xffffffff;
- }
- }
- }
- // 生成二维码图片的格式,使用ARGB_8888
- Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT, Bitmap.Config.ARGB_8888);
- bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT);
- return bitmap;
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
22.得到自定义进度框:
- /**
- * 得到自定义的progressDialog
- *
- * @param context
- * @param msg
- * @param bCancel
- * 按返回键是否取消
- * @return
- */
- public static Dialog createLoadingDialog(Context context, String msg, boolean bCancel) {
- LayoutInflater inflater = LayoutInflater.from(context);
- View v = inflater.inflate(R.layout.loading_dialog, null);// 得到加载view
- LinearLayout layout = (LinearLayout) v.findViewById(R.id.dialog_view);// 加载布局
- // main.xml中的ImageView
- ImageView spaceshipImage = (ImageView) v.findViewById(R.id.img);
- TextView tipTextView = (TextView) v.findViewById(R.id.tipTextView);// 提示文字
- // 加载动画
- Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(context, R.anim.loading_animation);
- // 使用ImageView显示动画
- spaceshipImage.startAnimation(hyperspaceJumpAnimation);
- tipTextView.setText(msg);// 设置加载信息
- Dialog loadingDialog = new Dialog(context, R.style.loading_dialog);// 创建自定义样式dialog
- loadingDialog.setCancelable(bCancel);// 不可以用“返回键”取消
- loadingDialog.setCanceledOnTouchOutside(false);
- loadingDialog.setContentView(layout, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));// 设置布局
- return loadingDialog;
- }
Android 开发实用方法大全的更多相关文章
- ANDROID开发实用小工具
分享一些 Android开发中的实用小工具,你有发现好工具吗? 来这里分享一下呗 一.find bugs 静态检查工具 http://findbugs.sourceforge.net/ FindBug ...
- Android 开发工具方法整理
1. 获取当前手机系统语言 Locale.getDefault().getLanguage(); 2. 获取当前手机系统版本号 android.os.Build.VERSION.RELEASE; 3. ...
- Android开发-- findViewById()方法得到空指针
如果想通过调用findViewById()方法获取到相应的控件,必须要求当前Activity的layout通过setContentView. 如果你通过其他方法添加了一个layout,如需获取这个la ...
- Android零基础入门第17节:Android开发第一个控件,TextView属性和方法大全
原文:Android零基础入门第17节:Android开发第一个控件,TextView属性和方法大全 前面简单学习了一些Android UI的一些基础知识,那么接下来我们一起来详细学习Android的 ...
- Android开发中,那些让您觉得相见恨晚的方法、类或接口
Android开发中,那些让你觉得相见恨晚的方法.类或接口本篇文章内容提取自知乎Android开发中,有哪些让你觉得相见恨晚的方法.类或接口?,其实有一部是JAVA的,但是在android开发中也算常 ...
- Android开发工具常用快捷键大全
Android开发中常用的开发工具有android studio和eclipse两种,下面小编整理了一些这两种开发工具中常用的快捷键,使用这些快捷键,你的android编程将事半功倍. android ...
- Android零基础入门第22节:ImageView的属性和方法大全
原文:Android零基础入门第22节:ImageView的属性和方法大全 通过前面几期的学习,TextView控件及其子控件基本学习完成,可以在Android屏幕上显示一些文字或者按钮,那么从本期开 ...
- [转]Android通过NDK调用JNI,使用opencv做本地c++代码开发配置方法
原文地址:http://blog.csdn.net/watkinsong/article/details/9849973 有一种方式不需要自己配置所有的Sun JDK, Android SDK以及ND ...
- 在android开发中使用multdex的方法-IT蓝豹为你整理
Android系统在安装应用时,往往需要优化Dex,而由于处理工具DexOpt对id数目的限制,导致其处理的数目不能超过65536个,因此在Android开发中,需要使用到MultiDex来解决这个问 ...
随机推荐
- Android—基于OpenCV+Android实现人脸检测
导读 OpenCV 是一个开源的跨平台计算机视觉库, 采C++语言编写,实现了图像处理和计算机视觉方面的很多通用算法,同时也提供对Python,Java,Android等的支持,这里利用Android ...
- nginx开机自启动
配置步骤:1 . vi /etc/init.d/nginx2. chkconfig --level nginx 2345 on --重点 --------------------以下为nginx配置文 ...
- [STL] 遍历删除两个vector中交集
#include <vector> #include <string> #include <algorithm> using namespace std; int ...
- BZOJ3522 POI2014HOT-Hotels(树形dp)
分两种情况.三点两两lca相同:在三点的lca处对其统计即可,显然其离lca距离应相同:某点在另两点lca的子树外部:对每个点统计出与其距离x的点有多少个即可. 可以长链剖分做到线性,当然不会. #i ...
- [bzoj1056] [HAOI2008]排名系统
Description 排名系统通常要应付三种请求:上传一条新的得分记录.查询某个玩家的当前排名以及返回某个区段内的排名记录.当某个玩家上传自己最新的得分记录时,他原有的得分记录会被删除.为了减轻服务 ...
- [bzoj5321] [Jxoi2017]加法
Description 可怜有一个长度为 n 的正整数序列 A,但是她觉得 A 中的数字太小了,这让她很不开心. 于是她选择了 m 个区间 [li, ri] 和两个正整数 a, k.她打算从这 m 个 ...
- 洛谷P1546 最短网络 Agri-Net
P1546 最短网络 Agri-Net 526通过 959提交 题目提供者JOHNKRAM 标签图论贪心USACO 难度普及/提高- 提交该题 讨论 题解 记录 最新讨论 50分C++代码,求解 请指 ...
- Dilworth定理证明
命题:偏序集能划分成的最少的全序集的个数与最大反链的元素个数相等. (离散数学结构第六版课本P245:把一个偏序集划分成具有全序的子集所需要的最少子集个数与元素在偏序下都是不可比的最大集合的基数之间有 ...
- angular js自定义service的简单示例
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" ...
- PHP报错Cannot adopt OID in UCD-SNMP-MIB、 LM-SENSORS-MIB
Cannot adopt OID in UCD-SNMP-MIB: Cannot adopt OID in LM-SENSORS-MIB: lmTempSensorsValue 运行PHP遇到这些错误 ...