博客
关于我
Android 开发常用的工具类(更新ing)
阅读量:623 次
发布时间:2019-03-13

本文共 5738 字,大约阅读时间需要 19 分钟。

Android开发实用工具与方法汇总

1. 测量View的宽高

增加View测量宽高的方法:

public static void measureWidthAndHeight(View view) {    int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);    int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);    view.measure(widthMeasureSpec, heightMeasureSpec);}

2. 压缩图片的方式

图片压缩需要谨慎处理:

public static Bitmap pressScaleCompress(Bitmap bitmap) {    ByteArrayOutputStream os = new ByteArrayOutputStream();    bitmap.compress(Bitmap.CompressFormat.PNG, 80, os);    byte[] bt = os.toByteArray();    Bitmap bitmap1 = BitmapFactory.decodeByteArray(bt, 0, bt.length);    return bitmap1;}

widthheight压缩方法:

public static Bitmap pressScaleWidthHeightCompress(Bitmap bitmap) {    Matrix matrix = new Matrix();    matrix.postScale(0.6f, 0.6f);    Bitmap bitmap1 = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);    return bitmap1;}

3. 倒计时工具类

倒计时工具实现:

public class CountDownUtils extends BaseCountDownTimer {    TextView tv;    public CountDownUtils(long millisInFuture, long countDownInterval, TextView tv) {        super(millisInFuture, countDownInterval);        this.tv = tv;    }    @Override    public void onTick(long millisUntilFinished) {        tv.setEnabled(false);        tv.setText("重新获取(" + millisUntilFinished / 1000 + "s)");    }    @Override    public void onFinish() {        tv.setText("重新验证");        tv.setEnabled(true);    }}

4. 清除缓存工具类

彻底清除缓存:

public static void clearAllCache(Context context) {    deleteDir(context.getCacheDir());    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {        deleteDir(context.getExternalCacheDir());    }}

deleteDir方法实现:

private static boolean deleteDir(File dir) {    if (dir != null && dir.isDirectory()) {        String[] children = dir.list();        for (int i = 0; i < children.length; i++) {            boolean success = deleteDir(new File(dir, children[i]));            if (!success) {                return false;            }        }    }    return dir.delete();}

5._DOUBLE精确计算工具类

避免Double精度问题:

public static double add(Double value1, Double value2) {    BigDecimal b1 = new BigDecimal(Double.toString(value1));    BigDecimal b2 = new BigDecimal(Double.toString(value2));    return b1.add(b2).doubleValue();}

6.图片保存到本地并返回路径

图片URIFile

public static String getRealPathFromUri(Context context, Uri uri) {    int sdkVersion = Build.VERSION.SDK_INT;    if (sdkVersion >= 19) {        return getRealPathFromUriAboveApi19(context, uri);    } else {        return getRealPathFromUriBelowAPI19(context, uri);    }}

getDataColumn方法:

private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {    String path = null;    String[] projection = {MediaStore.Images.Media.DATA};    Cursor cursor = null;    try {        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);        if (cursor != null && cursor.moveToFirst()) {            int columnIndex = cursor.getColumnIndexOrThrow(projection[0]);            path = cursor.getString(columnIndex);        }    } catch (Exception e) {        if (cursor != null) {            cursor.close();        }    }    return path;}

7.网络请求Retrofit工具类

高效网络请求工具:

public class RetrofitManager {    private static final String BASE_URL = "http://yb.dashuibei.com/index.php/Home/";    private static RetrofitManager instance = null;    private final Retrofit retrofit;    private RetrofitManager(String baseUrl) {        retrofit = new Retrofit.Builder()                .baseUrl(baseUrl)                .addConverterFactory(GsonConverterFactory.create())                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())                .client(buildOkHttpClient())                .build();    }    public static RetrofitManager getDefault() {        if (instance == null) {            instance = new RetrofitManager(BASE_URL);        }        return instance;    }    private OkHttpClient buildOkHttpClient() {        return new OkHttpClient.Builder()                .readTimeout(5000, TimeUnit.MILLISECONDS)                .writeTimeout(5000, TimeUnit.MILLISECONDS)                .connectTimeout(5000, TimeUnit.MILLISECONDS)                .build();    }}

8.关于时间

时间工具类实现:

public static String getStandardDate(String timeStr) {    long t = Long.parseLong(timeStr);    long currentTime = System.currentTimeMillis() - t * 1000;    StringBuilder sb = new StringBuilder();    long seconds = currentTime / 1000;    long minutes = (currentTime / 1000) / 60;    long hours = (currentTime / 1000) / 3600;    long days = (currentTime / 1000) / 86400;    if (days > 1) {        sb.append(String.format("%d天", days));    } else if (hours > 24) {        sb.append(String.format("1天"));    } else if (hours > 0) {        sb.append(String.format("%d小时", hours));    } else if (minutes > 0) {        sb.append(String.format("%d分钟", minutes));    } else if (seconds > 0) {        sb.append(String.format("%d秒", seconds));    } else {        sb.append("刚刚");    }    if (!sb.toString().equals("刚刚")) {        sb.append("前");    }    return sb.toString();}

9.ूष意工具类

关闭软键盘方法:

public static void closeKeyboard(Activity context) {    ((InputMethodManager) context.getSystemService(context.INPUT_METHOD_SERVICE))            .hideSoftInputFromWindow(context.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);}

10.杂

Base64图片转字符串:

public static String Bitmap2StrByBase64(Bitmap bit) {    ByteArrayOutputStream bos = new ByteArrayOutputStream();    bit.compress(Bitmap.CompressFormat.JPEG, 40, bos);    byte[] bytes = bos.toByteArray();    return Base64.encodeToString(bytes, Base64.DEFAULT);}

欢迎加入技术交流群,共同探讨更多Android开发技巧!

转载地址:http://ctyoz.baihongyu.com/

你可能感兴趣的文章
mysql执行顺序与索引算法
查看>>
mysql批量update优化_Mysql中,21个写SQL的好习惯,你值得拥有呀
查看>>
mysql批量update操作时出现锁表
查看>>
MYSQL批量UPDATE的两种方式
查看>>
mysql批量修改字段名(列名)
查看>>
MySQL批量插入数据遇到错误1213的解决方法
查看>>
mysql技能梳理
查看>>
MySQL报Got an error reading communication packets错
查看>>
Mysql报错Can‘t create/write to file ‘/tmp/#sql_3a8_0.MYD‘ (Errcode: 28 - No space left on device)
查看>>
MySql报错Deadlock found when trying to get lock; try restarting transaction 的问题解决
查看>>
MySQL报错ERROR 1045 (28000): Access denied for user ‘root‘@‘localhost‘
查看>>
Mysql报错Packet for query is too large问题解决
查看>>
mysql报错级别_更改MySQL日志错误级别记录非法登陆(Access denied)
查看>>
Mysql报错:too many connections
查看>>
MySQL报错:无法启动MySQL服务
查看>>
mysql授权用户,创建用户名密码,授权单个数据库,授权多个数据库
查看>>
mysql排序查询
查看>>
MySQL排序的艺术:你真的懂 Order By吗?
查看>>
MySQL排序的艺术:你真的懂 Order By吗?
查看>>
Mysql推荐书籍
查看>>