LayoutParams是什么?

LayoutParams主要保存了一个View的布局参数,因此可以使用LayoutParams来改变布局参数从而达到View位置的效果,一般在自定义View的时候使用。

LayoutParams怎么用?

  • 如果父控件是LinearLayout,需要使用LinearLayout.LayoutParams
    代码如下:
LinearLayout.LayoutParams layoutParams=(LinearLayout.LayoutParams)getLayoutParams();layoutParams.leftMargin=getLeft()+offsetX;layoutParams.topMargin=getTop()+offsetY;setLayoutParams(layoutParams)
  • 如果父控件是RelativeLayout的话,需要使用RelativeLayout.LayoutParams。
RelativeLayout.LayoutParams layoutParams=(RelativeLayout.LayoutParams)getLayoutParams();layoutParams.leftMargin=getLeft()+offsetX;layoutParams.topMargin=getTop()+offsetY;setLayoutParams(layoutParams)
  • 除了使用布局的LayoutParams外,我们还可以用ViewGroup.MarginLayoutParams来实现:
ViewGroup.MarginLayoutParams layoutParams=(ViewGroup.MarginLayoutParams)getLayoutParams();layoutParams.leftMargin=getLeft()+offsetX;layoutParams.topMargin=getTop()+offsetY;setLayoutParams(layoutParams);
  • 对于一些不需要寻找父View,自己new出一个View自定义的情况。
View line = null;LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 1);layoutParams.leftMargin = 10;line = new View(mContext);line.setBackgroundResource(R.color.color_tie_bg);addView(line, layoutParams);
  • 通过WindowManager.LayoutParams来实现,下面是一段获取设置Window大小的代码,例如在自定义Dialog的时候,onCreate方法中编写这段代码,从而设置dialog最后显示Window的大小。
 Window win = getWindow();        WindowManager.LayoutParams lp = win.getAttributes();        lp.height = DensityUtil.dip2px(mContext, 185);        lp.width = DensityUtil.dip2px(mContext, 280);        win.setAttributes(lp);

总结

以上是在开发过程中用到的一些LayoutParams相关的内容,后期会不断补充。

更多相关文章

  1. Android(安卓)TabLayout 结合ViewPager实现标签页切换
  2. 解决Android视频播放横竖屏切换播放问题!
  3. Android(安卓)自定义控件☞添加attr属性
  4. Android(安卓)Jetpack组件之DataBinding详解
  5. AndroidStudio部署项目时出现错误:Instant Run requires 'Tools |
  6. Android游戏开发系统控件-Dialog
  7. 统一样式的View应该用style修饰
  8. Android中Adapter嵌套Adapter、ListView嵌套GridView时的内层Ada
  9. DexHunter脱壳神器分析

随机推荐

  1. 2010.12.10(2)——— android 使用地图
  2. JS与Android(安卓)WebView的简单交互 + W
  3. Linux系统查看磁盘可用空间的5个命令
  4. localStorage改变背景颜色和字体大小
  5. 保留用户自定义设置
  6. 简易万年历
  7. vue 基础语法及购物车小案例
  8. 如何开始学习cg素描?动漫cg素描学习教学!
  9. android gridview 行高设置
  10. Android(安卓)Logging