android 适配

public class UIAdapter {
    private static volatile  UIAdapter instance = null;
    //设计师的参考尺寸
    private static final float defaultWidth = 1080;
    private static final float defaultHeight = 1920;
    //屏幕的真实尺寸
    private int screenWidth;
    private int screenHeight;
    private UIAdapter(){
 
    }
    public static UIAdapter getInstance(){
        if(null==instance){
            synchronized (UIAdapter.class){
                if(null==instance){
                    instance = new UIAdapter();
                }
            }
        }
        return instance;
    }
    public void init(Context context) {
        if(null==context){
            return;
        }
        WindowManager wm = (WindowManager) context.getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics displayMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(displayMetrics);
        if(displayMetrics.widthPixels>displayMetrics.heightPixels){//横屏
            screenWidth = displayMetrics.heightPixels;
            screenHeight = displayMetrics.widthPixels;
        }else{
            screenWidth = displayMetrics.widthPixels;
            screenHeight = displayMetrics.heightPixels-getStatusBarHeight(context);
        }
    }
    /**
     * 获取状态栏高度
     * @param context
     * @return
     */
    public static int getStatusBarHeight(Context context) {
        Resources resources = context.getResources();
        int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
        int height = resources.getDimensionPixelSize(resourceId);
        return height;
    }
    public  float scaleX(){
        return screenWidth/defaultWidth;
    }
    public  float scaleY(){
        return screenHeight/defaultHeight;
    }
    public void scaleView(View v, int w, int h, int l, int t, int r, int b) {
        if(v==null){
            return;
        }
        w = (int) (w*scaleX());
        h = (int) (h*scaleY());
        l = (int) (l*scaleX());
        t = (int) (t*scaleY());
        r = (int) (r*scaleX());
        b = (int) (b*scaleY());
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
        if (params != null) {
            params.width = w;
            params.height = h;
            params.setMargins(l, t, r, b);
        }
    }
}

记得在Application初始化下

 
public class MyApp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        UIAdapter.getInstance().init(this);
    }
}


 UIAdapter.getInstance().scaleView(textview,540,200,0,0,0,0);

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值