ITPub博客

首页 > IT职业 > IT生活 > 项目框架工具类(UIUtils)

项目框架工具类(UIUtils)

IT生活 作者:keehoo 时间:2021-09-09 08:59:51 0 删除 编辑
/**
 * 工具类, 专门用来获取UI相关需要的参数
 * 
 * @author Kevin
 * 
 */
public class UIUtils {

public static Context getContext() {
    return BaseApplication.getContext();//BaseApplication为我们自定义的Application,里面初始化了一些静态全局变量!
}

public static int getMainThreadId() {
    return BaseApplication.getMainThreadId();
}

public static Handler getHandler() {
    return BaseApplication.getHandler();
}

/**
 * 根据id获取字符串
 */
public static String getString(int id) {
    return getContext().getResources().getString(id);
}

/**
 * 根据id获取图片
 */
public static Drawable getDrawable(int id) {
    return getContext().getResources().getDrawable(id);
}

/**
 * 根据id获取颜色值
 */
public static int getColor(int id) {
    return getContext().getResources().getColor(id);
}

/**
 * 获取颜色状态集合
 */
public static ColorStateList getColorStateList(int id) {
    return getContext().getResources().getColorStateList(id);
}

/**
 * 根据id获取尺寸
 */
public static int getDimen(int id) {
    return getContext().getResources().getDimensionPixelSize(id);
}

/**
 * 根据id获取字符串数组
 */
public static String[] getStringArray(int id) {
    return getContext().getResources().getStringArray(id);
}

/**
 * dp转px
 */
public static int dip2px(float dp) {
    float density = getContext().getResources().getDisplayMetrics().density;
    return (int) (density * dp + 0.5);
}

/**
 * px转dp
 */
public static float px2dip(float px) {
    float density = getContext().getResources().getDisplayMetrics().density;
    return px / density;
}

/**
 * 加载布局文件
 */
public static View inflate(int layoutId) {
    return View.inflate(getContext(), layoutId, null);
}

/**
 * 判断当前是否运行在主线程
 * 
 * @return
 */
public static boolean isRunOnUiThread() {
    return getMainThreadId() == android.os.Process.myTid();
}

/**
 * 保证当前的操作运行在UI主线程
 * 
 * @param runnable
 */
public static void runOnUiThread(Runnable runnable) {    
    if (isRunOnUiThread()) {
        runnable.run();
        } else {
            getHandler().post(runnable);
        }
    }
}

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4357/viewspace-2807567/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-12

  • 博文量
    0
  • 访问量
    632