LayoutParams基本使用
16lz
2021-01-26
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相关的内容,后期会不断补充。
更多相关文章
- Android(安卓)TabLayout 结合ViewPager实现标签页切换
- 解决Android视频播放横竖屏切换播放问题!
- Android(安卓)自定义控件☞添加attr属性
- Android(安卓)Jetpack组件之DataBinding详解
- AndroidStudio部署项目时出现错误:Instant Run requires 'Tools |
- Android游戏开发系统控件-Dialog
- 统一样式的View应该用style修饰
- Android中Adapter嵌套Adapter、ListView嵌套GridView时的内层Ada
- DexHunter脱壳神器分析