1,在Application中获取context:
好处是在整个项目中都可以使用,
public class MyApplication extends Application {
private static MyApplication baseApp;
public static Context getContext() {
return baseApp;
}
}
2.dp转换px
public static int dip2px(int dip) {
final float scale = MyApplication.getContext().getResources().getDisplayMetrics().density;
return (int) (dip * scale + 0.5f);
}
3.px转换dp
public static int px2dip(int px) {
final float scale = MyApplication.getContext().getResources().getDisplayMetrics().density;
return (int) (px / scale + 0.5f);
}