簡單說說 自己對 android LayoutParams的理解吧,xh寫不出高級文章是低級寫手。
public static class
ViewGroup.LayoutParams
extends Object
java.lang.Object
↳ android.view.ViewGroup.LayoutParams //繼承關系
以下說明摘自官方文檔E文好的可以看看
Class Overview
LayoutParams 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 number
There 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 怎么查看源碼 請看http://byandby.iteye.com/blog/814277
下邊來個例子
- //創建一個線性布局
- 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);
- //比較簡單的一個例子
如果還不能理解下邊在來一段直白的說明:
LayoutParams繼承於Android.View.ViewGroup.LayoutParams.
LayoutParams相當於一個Layout的信息包,它封裝了Layout的位置、高、寬等信息。假設在屏幕上一塊區域是由一個Layout占領的,如果將一個View添加到一個Layout中,最好告訴Layout用戶期望的布局方式,也就是將一個認可的layoutParams傳遞進去。
可以這樣去形容LayoutParams,在象棋的棋盤上,每個棋子都占據一個位置,也就是每個棋子都有一個位置的信息,如這個棋子在4行4列,這里的“4行4列”就是棋子的LayoutParams。
但LayoutParams類也只是簡單的描述了寬高,寬和高都可以設置成三種值:
1,一個確定的值;
2,FILL_PARENT,即填滿(和父容器一樣大小);
3,WRAP_CONTENT,即包裹住組件就好。
關於setLayoutParams報錯
在繼承BaseAdapter的時候,用getView返回View的時候,用代碼控制布局,需要用到View.setLayoutParams,但是報錯了,報的是類型轉換錯誤,經過研究,發現,這里不能使用ViewGroup.LayoutParams而必須使用對應父View的LayoutParams類型。如:某View被LinearLayout包含,則該View的setLayoutParams參數類型必須是LinearLayout.LayoutParams。原因在於LinearLayout(或其他繼承自ViewGroup的layout,如:RelativeLayout)在進行遞歸布局的時候,LinearLayout會獲取子View的LayoutParams,並強制轉換成LinearLayout.LayoutParams,如
或者是如下定義:
以轉換成內部類型LinearLayout.LayoutParams。