/** * 专门提供为处理一些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
}
}