分类: 2012-04-25 20:04 3794人阅读 (2)
简单说说 自己对 android LayoutParams的理解吧,xh写不出高级文章是低级写手。
public static classViewGroup.LayoutParamsextends Objectjava.lang.Object ↳ android.view.ViewGroup.LayoutParams //继承关系以下说明摘自官方文档E文好的可以看看Class OverviewLayoutParams are used by views to tell their parents how they want to be laid out. See ViewGroup Layout Attributes for a list of all child view attributes that this class supports.The base LayoutParams class just describes how big the view wants to be for both width and height. For each dimension, it can specify one of:FILL_PARENT (renamed MATCH_PARENT in API Level 8 and higher), which means that the view wants to be as big as its parent (minus padding)WRAP_CONTENT, which means that the view wants to be just big enough to enclose its content (plus padding)an exact numberThere are subclasses of LayoutParams for different subclasses of ViewGroup. For example, AbsoluteLayout has its own subclass of LayoutParams which adds an X and Y value.E文不好看不懂 但是觉得写得啰嗦了其实这个LayoutParams类是用于child view(子视图) 向 parent view(父视图)传达自己的意愿的一个东西(孩子想变成什么样向其父亲说明)其实子视图父视图可以简单理解成一个LinearLayout 和 这个LinearLayout里边一个 TextView 的关系 TextView 就算LinearLayout的子视图 child view 。需要注意的是LayoutParams只是ViewGroup的一个内部类这里边这个也就是ViewGroup里边这个LayoutParams类是 base class 基类实际上每个不同的ViewGroup都有自己的LayoutParams子类比如LinearLayout 也有自己的 LayoutParams 大家打开源码看几眼就知道了myeclipse 怎么查看源码 请看下边来个例子 Java代码 :
- //创建一个线性布局
- private LinearLayout mLayout;
- mLayout = (LinearLayout) findViewById(R.id.layout);
- //现在我要往mLayout里边添加一个TextView
- //你可能会想直接在布局文件里边配置不就O 了 那是 但是这里为了说明问题我们用代码实现
- TextView textView = new TextView(Activity01.this);
- textView.setText("Text View " );
- //这里请不要困惑这里是设置 这个textView的布局 FILL_PARENT WRAP_CONTENT 和在xml文件里边设置是一样的如
- //在xml里边怎么配置高宽大家都会的。
- //第一个参数为宽的设置,第二个参数为高的设置。
- LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
- LinearLayout.LayoutParams.FILL_PARENT,
- LinearLayout.LayoutParams.WRAP_CONTENT
- );
- //调用addView()方法增加一个TextView到线性布局中
- mLayout.addView(textView, p);
- //比较简单的一个例子
在继承BaseAdapter的时候,用getView返回View的时候,用代码控制布局,需要用到View.setLayoutParams,但是报错了,报的是类型转换错误,经过研究,发现,这里不能使用ViewGroup.LayoutParams而必须使用对应父View的LayoutParams类型。如:某View被LinearLayout包含,则该View的setLayoutParams参数类型必须是LinearLayout.LayoutParams。原因在于LinearLayout(或其他继承自ViewGroup的layout,如:RelativeLayout)在进行递归布局的时候,LinearLayout会获取子View的LayoutParams,并强制转换成LinearLayout.LayoutParams,如
1 LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) child.getLayoutParams();
或者是如下定义:
1 LayoutParams lp = (LayoutParams) child.getLayoutParams();
以转换成内部类型LinearLayout.LayoutParams。