AutoScreenAdaptation
安卓屏幕适配 项目直接用dp和sp的可以不用改动 直接加入一句代码即可实现适配
还未确定会不会有兼容性问题和性能问题 需要时间测试
目前测试过模拟器的不同分辨率和不同dpi基本效果不会差太多
旋转屏幕 布局会按横版的大小缩放 视图也不会乱
支持x y适配
效果图
主要代码
public classScreenAdaptation {
privateApplication.ActivityLifecycleCallbacksactivityLifecycleCallbacks;
privateApplicationmApplication;
private floatmWidth=720;
private floatmHeight=1280;
publicScreenAdaptation(Application application,floatwidth,intheight) {
mApplication= application;
mWidth= width;
mHeight= height;
activityLifecycleCallbacks=newApplication.ActivityLifecycleCallbacks() {
@Override
public voidonActivityCreated(Activity activity, Bundle savedInstanceState) {
//开启Activity才执行
resetDensity(activity,mWidth,mHeight);
}
@Override
public voidonActivityStarted(Activity activity) {
}
@Override
public voidonActivityResumed(Activity activity) {
}
@Override
public voidonActivityPaused(Activity activity) {
}
@Override
public voidonActivityStopped(Activity activity) {
}
@Override
public voidonActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public voidonActivityDestroyed(Activity activity) {
}
};
}
/**
*注册
*/
public voidregister(){
resetDensity(mApplication,mWidth,mHeight);
mApplication.registerActivityLifecycleCallbacks(activityLifecycleCallbacks);
}
/**
*注销
*/
public voidunregister(){
//设置为默认
mApplication.getResources().getDisplayMetrics().setToDefaults();
mApplication.unregisterActivityLifecycleCallbacks(activityLifecycleCallbacks);
}
/**
* dp适配getResources().getDisplayMetrics().density
* sp适配getResources().getDisplayMetrics().scaledDensity
* pt适配getResources().getDisplayMetrics().xdpi
*@paramcontext
*@paramwidthui设计图的宽度
*@paramheightui设计图的高度
*/
private static voidresetDensity(Context context,floatwidth ,floatheight){
Point point =newPoint();
//获取屏幕的数值
((WindowManager)context.getSystemService(WINDOW_SERVICE)).getDefaultDisplay().getSize(point);
//dp适配getResources().getDisplayMetrics().density
context.getResources().getDisplayMetrics().density= point.x/width*2f;
context.getResources().getDisplayMetrics().density= point.y/height*2f;
//sp适配getResources().getDisplayMetrics().scaledDensity
context.getResources().getDisplayMetrics().scaledDensity= point.x/width*2f;
context.getResources().getDisplayMetrics().scaledDensity= point.y/height*2f;
}
}
使用:
public classAppextendsApplication{
@Override
public voidonCreate() {
super.onCreate();
//需要传入ui设计给的大小,初始化
newScreenAdaptation(this,720,1280).register();
}
}
Demo链接:github.com/wenkaichuang0729/AutoScreenAdaptation