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

来源:互联网 发布:javascript分割字符串 编辑:程序博客网 时间:2024/06/14 22:21
 /**  * 专门提供为处理一些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转化为pxpublic 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;//需要使用的handlerpublic static Thread mainThread;//提供主线程对象public static int mainThreadId;//提供主线程对象的id@Overridepublic void onCreate() {    super.onCreate();    context = this.getApplicationContext();    handler = new Handler();    mainThread = Thread.currentThread();//实例化当前Application的线程即为主线程    mainThreadId = android.os.Process.myTid();//获取当前线程的id   }} 
阅读全文
0 0
原创粉丝点击