专门提供为处理一些UI相关的问题而创建的工具类

 /**
  * 专门提供为处理一些UI相关的问题而创建的工具类,
  * 提供资源获取的通用方法,避免每次都写重复的代码获取结果。
 */
public class UIUtils {

public static Context getContext() {
    return MyApplication.context;
}

public static Handler getHandler() {
    return MyApplication.handler;
}

//返回指定colorId对应的颜色值
public static int getColor(int colorId) {
    return getContext().getResources().getColor(colorId);
}

//加载指定viewId的视图对象,并返回
public static View getView(int viewId) {
    View view = View.inflate(getContext(), viewId, null);
    return view;
}

public static String[] getStringArr(int strArrId) {
    String[] stringArray = getContext().getResources().getStringArray(strArrId);
    return stringArray;
}

//将dp转化为px
public static int dp2px(int dp) {
    //获取手机密度
    float density = getContext().getResources().getDisplayMetrics().density;
    return (int) (dp * density + 0.5);//实现四舍五入
}

public static int px2dp(int px) {
    //获取手机密度
    float density = getContext().getResources().getDisplayMetrics().density;
    return (int) (px / density + 0.5);//实现四舍五入
}

/**
 * 保证运行在主线程
 *
 */
public static void runOnUiThread(Runnable runnable) {
    if (isMainThread()) {
        runnable.run();
    } else {
        UIUtils.getHandler().post(runnable);
    }
}

//判断当前线程是否是主线程
private static boolean isMainThread() {
    int currentThread = Process.myTid();

    return currentThread == MyApplication.mainThreadId;// mainThreadId = android.os.Process.myTid()
}

MyApplication类 public class MyApplication extends Application {

//在整个应用执行过程中,需要提供的变量
public static Context context;//需要使用的上下文对象
public static Handler handler;//需要使用的handler
public static Thread mainThread;//提供主线程对象
public static int mainThreadId;//提供主线程对象的id

@Override
public void onCreate() {
    super.onCreate();

    context = this.getApplicationContext();
    handler = new Handler();
    mainThread = Thread.currentThread();//实例化当前Application的线程即为主线程
    mainThreadId = android.os.Process.myTid();//获取当前线程的id
   }
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值