这篇文章主要介绍了Android LayoutParams使用案例详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下
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 LayoutParams使用案例详解的文章就介绍到这了,更多相关Android LayoutParams使用内容请搜索编程学习网以前的文章希望大家以后多多支持编程学习网!
织梦狗教程
本文标题为:Android LayoutParams使用案例详解


基础教程推荐
猜你喜欢
- Flutter手势密码的实现示例(附demo) 2023-04-11
- IOS 播放系统提示音使用总结(AudioToolbox) 2023-03-01
- 解决Android Studio突然不显示logcat日志的问题 2023-02-04
- Android多返回栈技术 2023-04-15
- iOS开发教程之XLForm的基本使用方法 2023-05-01
- Android开发使用RecyclerView添加点击事件实例详解 2023-06-15
- Android中的webview监听每次URL变化实例 2023-01-23
- android studio按钮监听的5种方法实例详解 2023-01-12
- IOS应用内跳转系统设置相关界面的方法 2022-11-20
- Flutter绘图组件之CustomPaint使用详解 2023-05-12