Andorid开发之常用工具类utils
Android项目中开发中常用的一些方法比如,加载布局、dp和px互转、添加字符串数组、获取图片等方法,我们可以创建一个工具类,代码如下:
package pengchao.p2pmoney.Utils;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.view.View;
import android.widget.Toast;
import pengchao.p2pmoney.common.MyApplication;
/**
* Created by Administrator on 2018/2/10.
*/
public class UIUtils {
public static Context getContext(){
return MyApplication.context;
}
public static Handler getHandler(){
return MyApplication.handler;
}
public static int getMainThreadId(){
return MyApplication.mainThreadId;
}
public static Thread getMainThread(){
return MyApplication.mainThread;
}
/**
* 获取资源
* @param id
* @return
*/
//获取字符串
public static String getString(int id){
return getContext().getResources().getString(id);
}
//获取字符串数组
public static String[] getStringArray(int id){
return getContext().getResources().getStringArray(id);
}
//获取图片
public static Drawable getDrawable(int id){
return getContext().getResources().getDrawable(id);
}
//获取颜色
public static int getColor(int id){
return getContext().getResources().getColor(id);
}
//根据id获取颜色的状态选择器
public static ColorStateList getColorStateList(int mTabTextColorResId) {
return getContext().getResources().getColorStateList(mTabTextColorResId);
}
//获取尺寸
public static int getDimen(int id){
return getContext().getResources().getDimensionPixelSize(id);//直接返回的像素值
}
/**
* dp和px转换
* @param dip
* @return
*/
public static int dip2px(float dip){
float density = getContext().getResources().getDisplayMetrics().density;//设备密度
return (int) (dip*density + 0.5f);
}
public static float px2dip(int px){
float density = getContext().getResources().getDisplayMetrics().density;//设备密度
return px/density;
}
/**
* 加载布局文件
* @param id
* @return
*/
public static View inflate(int id){
return View.inflate(getContext(), id, null);
}
/**
* 判断是否运行在主线程
* @return
*/
public static boolean isRunOnUIThread(){
//获取当前线程id,如果当前id和主线程id一致就运行在主线程
int myTid = android.os.Process.myTid();
if(myTid == getMainThreadId()){
return true;
}
return false;
}
//运行在主线程
public static void runOnUIThread(Runnable r){
if(isRunOnUIThread()){
r.run();
}else{
//如果是子线程,借助handler让其运行在主线程
getHandler().post(r);
}
}
}