Android LayoutParams使用 Android LayoutParams使用案例详解

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Android LayoutParams使用 Android LayoutParams使用案例详解

傲娇的koala   2021-08-25 我要评论
想了解Android LayoutParams使用案例详解的相关内容吗,傲娇的koala在本文为您仔细讲解Android LayoutParams使用的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Android,LayoutParams使用,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相关的内容,后期会不断补充。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们