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

这里是用ConstraintLayout布局

布局xml:

<?xml version="1.0" encoding="utf-8"?>                                                                

后台代码:

        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转换为pxint dip2px(Context context, float dpValue) {    final float scale = context.getResources().getDisplayMetrics().density;    return (int) (dpValue * scale + 0.5f);}

 

更多相关文章

  1. Android(安卓)显示手机电池的当前电量
  2. Android(安卓)-- CursorAdapter
  3. Android(安卓)代码提示无效
  4. android内存溢出的解决方法
  5. Android(安卓)水波纹扩散效果
  6. android模仿微信朋友圈图片预览转场缩放动画
  7. Android的Layout --- 布局
  8. Android(安卓)动画 - ScaleAnimation 缩放动画使用(附图)
  9. Android开发常见错误及技巧

随机推荐

  1. android 语音识别接口开发。
  2. Android客户端嵌入html5页面
  3. Android(安卓)Asynchronous Http Client
  4. android 内部注册receiver
  5. Android快速显示4G
  6. Android(安卓)O(android 8.1) SYSTEM_UID应
  7. android opengl es 七彩星星效果
  8. Android(安卓)关闭所有Activity完全退出
  9. 【AndroidStudio】Aapt2Exception
  10. Android(安卓)OnTouchListener 触摸事件