Android 工具类,持续更新

来源:互联网 发布:涂鸦照片的软件 编辑:程序博客网 时间:2024/05/02 04:50

1.判断是否为平板的方法

/**     * 判断是否为平板     *     * @return     */    public static boolean isPad(Activity activity) {        WindowManager wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);        Display display = wm.getDefaultDisplay();        // 屏幕宽度        float screenWidth = display.getWidth();        // 屏幕高度        float screenHeight = display.getHeight();        DisplayMetrics dm = new DisplayMetrics();        display.getMetrics(dm);        double x = Math.pow(dm.widthPixels / dm.xdpi, 2);        double y = Math.pow(dm.heightPixels / dm.ydpi, 2);        // 屏幕尺寸        double screenInches = Math.sqrt(x + y);        // 大于6尺寸则为Pad        if (screenInches >= 6.0) {            return true;        }        return false;    }

2.dp 转 px

/** dp值转px值 */    public static int dp2px(Activity activity, Integer width){        Resources resources = activity.getResources();        float fPx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, width, resources.getDisplayMetrics());        int iPx = Math.round(fPx);        return iPx;    }    /**     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)     */    public static int dip2px(Context context, Integer dpValue) {        final float scale = context.getResources().getDisplayMetrics().density;        return (int) (dpValue * scale + 0.5f);    }

3.文本自动换行

private static String autoSplitText(final TextView tv) {        final String rawText = tv.getText().toString(); //原始文本        final Paint tvPaint = tv.getPaint(); //paint,包含字体等信息        final float tvWidth = tv.getWidth() - tv.getPaddingLeft() - tv.getPaddingRight(); //控件可用宽度        //将原始文本按行拆分        String [] rawTextLines = rawText.replaceAll("\r", "").split("\n");        StringBuilder sbNewText = new StringBuilder();        for (String rawTextLine : rawTextLines) {            if (tvPaint.measureText(rawTextLine) <= tvWidth) {                //如果整行宽度在控件可用宽度之内,就不处理了                sbNewText.append(rawTextLine);            } else {                //如果整行宽度超过控件可用宽度,则按字符测量,在超过可用宽度的前一个字符处手动换行                float lineWidth = 0;                for (int cnt = 0; cnt != rawTextLine.length(); ++cnt) {                    char ch = rawTextLine.charAt(cnt);                    lineWidth += tvPaint.measureText(String.valueOf(ch));                    if (lineWidth <= tvWidth) {                        sbNewText.append(ch);                    } else {                        sbNewText.append("\n");                        lineWidth = 0;                        --cnt;                    }                }            }            sbNewText.append("\n");        }        //把结尾多余的\n去掉        if (!rawText.endsWith("\n")) {            sbNewText.deleteCharAt(sbNewText.length() - 1);        }        return sbNewText.toString();    }


0 0
原创粉丝点击