首页 > 系统 > Android > 正文

Android LayoutParams用法解析

2019-11-09 17:36:07
字体:
来源:转载
供稿:网友

ViewGroup.LayoutParams介绍

LayoutParams携带了子控件针对父控件的信息,告诉父控件如何放置自己

LayoutParams类也只是简单的描述了宽高,宽和高都可以设置成三种值: 1,一个确定的值; 2,FILL_PARENT,即填满(和父容器一样大小); 3,WRAP_CONTENT,即包裹住组件就好。

每一个ViewGroup(例如LinearLayout, RelativeLayout, CoordinatorLayout, etc)需要存储有关其孩子view的属性信息。它的孩子view被放在ViewGroup,这些位置信息存储在一个包装类viewgroup.layoutparams对象中。 为了包含一个特定的布局的具体参数,viewgroup使用layoutparams Viewgroup类的子类来存储。 例如 linearlayout.layoutparams relativelayout.layoutparams coordinatorlayout.layoutparams

对于margin有一个ViewGroup.MarginLayoutParams类代替ViewGroup.LayoutParams。

获取ViewGroup.LayoutParams

getLayoutParams()方法可以获取ViewGroup.LayoutParams对象。

举例如下

public class ExampleView extends View { public ExampleView(Context context) { super(context); setupView(context); } public ExampleView(Context context, AttributeSet attrs) { super(context, attrs); setupView(context); } public ExampleView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setupView(context); } PRivate void setupView(Context context) { if (getLayoutParams().height == 50){ // DO NOT DO THIS! // This might produce NullPointerException doSomething(); } } //...}

ViewGroup.LayoutParams上下转型

注意LayoutParams携带了子控件针对父控件的信息,告诉父控件如何放置自己,所以要使用相应父控件的LayoutParams。

举例说明,一个LinearLayout包含FrameLayout 错误使用

FrameLayout innerLayout = (FrameLayout)findViewById(R.id.inner_layout);FrameLayout.LayoutParams par = (FrameLayout.LayoutParams) innerLayout.getLayoutParams();

正确的使用

FrameLayout innerLayout = (FrameLayout)findViewById(R.id.inner_layout);LinearLayout.LayoutParams par = (LinearLayout.LayoutParams) innerLayout.getLayoutParams();

我的微信二维码如下

这里写图片描述

微信订阅号二维码如下:

这里写图片描述


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表