android 动态设置margin

代码中不能直接给控件设置margin属性,可以通过layoutParam来设置

这里是用ConstraintLayout布局

布局xml:



    
    
    

    
    
    
    
    

    


    
    

    

        
    

    

后台代码:

        WindowManager wm = (WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        int height = wm.getDefaultDisplay().getHeight();
        
        //遍历界面上的控件 
        ConstraintLayout rootView = (ConstraintLayout)findViewById(R.id.rootView);
        for (int i = 0; i < rootView.getChildCount(); i++) {
            View v=rootView.getChildAt(i);
            ConstraintLayout.LayoutParams layoutParam =(ConstraintLayout.LayoutParams)v.getLayoutParams();
            switch(height)
            {
                case 800:
                    //指定控件类型设置
                    if( !(v instanceof HorizontalScrollView)&&!(v instanceof ListView))
                        layoutParam.height = dip2px(this, 40);
                    else
                        layoutParam.height = dip2px(this, 100);
                    if(i==0||i==1)//设置第一和第二个控件topMargin
                        layoutParam.topMargin=dip2px(this, 10);
                    break;
                case 1520:
                    if( !(v instanceof HorizontalScrollView)&&!(v instanceof ListView))
                        layoutParam.height = dip2px(this, 50);
                    else
                        layoutParam.height = dip2px(this, 200);
                    if(i==0||i==1)
                        layoutParam.topMargin=dip2px(this, 33);
                    break;
                default:
                    break;
            }
        }

//db转换为px
int dip2px(Context context, float dpValue) {
    final float scale = context.getResources().getDisplayMetrics().density;
    return (int) (dpValue * scale + 0.5f);
}

 

你可能感兴趣的:(Android)