自己封裝的一個工具類

工具類包含的方法:
1.dip到px的轉換;
2.2.讓代碼運行到主進程的方法;
3.3.獲取隨機顏色的值的方法;
4.4.獲取一個帶背景顏色的圓角矩形的方法;
5.設置背景選擇器的方法;
6.6.生成隨機的不重複的id值的方法;
7.7.通過資源id獲取資源圖片的方法;
8.8.判斷是否是主線程的方法;

public class UIUtil {
/**像素轉換:
* @param dip 要轉換的dip格式的數值;
* @return 轉換後的px格式的數值
* */
public static int dip2px(int dip) {
// 通過GoogleApplication的靜態方法獲取上下文
Context context = MyApplication.getContext();
// 獲取密度density
float density = context.getResources().getDisplayMetrics().density;
// dip*density+0.5
int px = (int) (dip * density + 0.5);
return px;
}
/**運行任務在主線程的方法:
* @param task 要執行到主線程的任務代碼
* */
public static void runInMainThread(Runnable task){
//判斷當前線程(android.os.Process.myTid)是否是主線程 若是,則直接調用task的run方法;task.run();
if (MyApplication.getMainThreadId() == android.os.Process.myTid()) {
task.run();
}else{
//否則 ,獲取主線程handler,把task交給主線程post(task)
MyApplication.getMainHandler().post(task);
}
}
/**獲取隨機顏色的方法:沒有黑色及白色
* */
public static int getRandomColor(){
int red = 10 + new Random().nextInt(240);
int green = 10 + new Random().nextInt(240);
int blue = 10 + new Random().nextInt(240);
int rgb = Color.rgb(red, green, blue);
return rgb;
}
/*獲取隨機大小的方法/
public static int getRandomSize(int min,int max){
int randomSize = min+new Random(max).nextInt();
return randomSize;
}
/**獲取一個帶背景顏色的圓角矩形的方法:
* 不設置邊緣會有一些位置的bug出現
* @param rgb 顏色的值
* */
public static GradientDrawable getGradientDrawable(int rgb) {
//創建圖形對象
GradientDrawable drawable = new GradientDrawable();
//定義圖形類型爲矩形
drawable.setGradientType(GradientDrawable.RECTANGLE);
//定義圓角大小
drawable.setCornerRadius(10.0f);
//定義圖形的顏色
drawable.setColor(rgb);
//設置圖形的邊緣線的寬度和顏色
drawable.setStroke(1, rgb);
//返回圖形對象
return drawable;
}
/**設置背景選擇器的方法
* @param pressedDrawable 被點擊時的背景顏色
* @param normalDrawable 普通狀態時的背景顏色
* */
public static StateListDrawable getStateListDrawable(
GradientDrawable pressedDrawable, GradientDrawable normalDrawable) {
//創建選擇器類對象
StateListDrawable drawable = new StateListDrawable();
//設置按下狀態時的背景
drawable.addState(new int[]{android.R.attr.state_pressed}, pressedDrawable);
//設置默認狀態時的背景
drawable.addState(new int[]{}, normalDrawable);
//返回選擇器
return drawable;
}
//
private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
/*生成隨機的不重複的id值的方法/
public static int generateViewId() {
for (;;) {
final int result = sNextGeneratedId.get();
int newValue = result + 1;
if (newValue > 0x00FFFFFF)
newValue = 1;
if (sNextGeneratedId.compareAndSet(result, newValue)) {
return result;
}
}
}
/*通過資源id獲取資源圖片的方法/
public static Drawable getDrawable(int mDrawableForegroudResId) {
return MyApplication.getContext().getResources().getDrawable(mDrawableForegroudResId);
}
/*判斷是否是主線程的方法/
public static boolean isInMainThread() {
//判斷主線程的id與當前線程的id是否一致
return MyApplication.getMainThreadId() == android.os.Process.myTid();
}
}

發佈了41 篇原創文章 · 獲贊 8 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章