android 动态设置margin
16lz
2021-01-24
代码中不能直接给控件设置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);}
更多相关文章
- Android(安卓)显示手机电池的当前电量
- Android(安卓)-- CursorAdapter
- Android(安卓)代码提示无效
- android内存溢出的解决方法
- Android(安卓)水波纹扩散效果
- android模仿微信朋友圈图片预览转场缩放动画
- Android的Layout --- 布局
- Android(安卓)动画 - ScaleAnimation 缩放动画使用(附图)
- Android开发常见错误及技巧