首页 > 其他 > 详细

常用的一些基础工具类

时间:2016-05-28 10:05:06      阅读:206      评论:0      收藏:0      [点我收藏+]

public class UiUtils {
    
    public static Context getContext(){
        return MyApplication.getContext();
    }
    
    public static Handler getMainThreadHandler() {
        return MyApplication.getHandler();
    }
    
    public static int getMainThreadId() {
        return MyApplication.getMainThreadId();
    }
    public static String[] getStringArray(int resId) {
        return getContext().getResources().getStringArray(resId);
    }

    // 获取drawable
    public static Drawable getDrawable(int resId) {
        return getContext().getResources().getDrawable(resId);
    }

    // 获取color的值
    public static int getColor(int resId) {
        return getContext().getResources().getColor(resId);
    }

    // 获取颜色的状态选择器
    public static ColorStateList getColorStateList(int resId) {
        return getContext().getResources().getColorStateList(resId);
    }

    // 获取dimen下定义的值
    public static int getDimen(int resId) {
        return getContext().getResources().getDimensionPixelSize(resId);
    }

    // dp--px
    public static int dp2px(int dp) {
        // 1、获取屏幕密度
        float density = getContext().getResources().getDisplayMetrics().density;
        // 2、进行乘法操作
        return (int) (dp * density + 0.5);
    }

    // px--dp
    public static int px2dp(int px) {
        // 1、获取屏幕密度
        float density = getContext().getResources().getDisplayMetrics().density;
        // 2、进行除法操作
        return (int) (px / density + 0.5);
    }

    // 判断当前线程是否处于主线程
    public static boolean isRunOnUiThread() {
        // 1、获取当前线程的线程id
        int currentThreadId = android.os.Process.myTid();
        // 2、获取主线程的线程id
        int mainThreadId = getMainThreadId();
        // 3、比较
        return currentThreadId == mainThreadId;
    }

    // 保证传递进来的r一定是在主线程中运行
    public static void runOnUiThread(Runnable r) {
        if (isRunOnUiThread()) {
            r.run();
            // new Thread(r).start();//此时启动了子线程
        } else {
            getMainThreadHandler().post(r);// 将r丢到了主线程的消息队列当中
        }
    }
    
    public static View inflate(int resId) {
        View view = View.inflate(getContext(), resId, null);
        return view;
    }

}

常用的一些基础工具类

原文:http://www.cnblogs.com/androidSun/p/5536818.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!