轉自:http://android.yaohuiji.com/archives/299
android2.2開始增加了match_parent這個屬性,這個屬性和原來的fill_parent一樣,
如果作程式時,向考慮自己的程式向下相容的話,就要用fill_parent,
下面是兩者相同的證據,看android.view.ViewGroup裡的靜態嵌套類LayoutParams中的代碼:
public static final int FILL_PARENT = -1; /** * Special value for the height or width requested by a View. * MATCH_PARENT means that the view wants to be as big as its parent, * minus the parent's padding, if any. Introduced in API Level 8. */ public static final int MATCH_PARENT = -1; /** * Special value for the height or width requested by a View. * WRAP_CONTENT means that the view wants to be just large enough to fit * its own internal content, taking its own padding into account. */
圖是協助文檔中的關於介面開發的推薦色值,大家可以參考一下:
android:gravity和android:layout_gravity區別
從名字上可以看到,android:gravity是對元素本身說的,元素本身的文本顯示在什麼地方靠著換個屬性設定,不過不設定預設是在左側的。android:layout_gravity是相對與它的父元素說的,說明元素顯示在父元素的什麼位置。
在Android中使用自訂圖片按鈕
(本節內容基本上是官方文檔的翻譯,看過官方文檔的朋友可以直接略過。)
在這一節裡,我們將使用一個button組件,一個xml檔案和三個圖片來製作一個自訂的按鈕,當按鈕按下的時候會有一個氣泡訊息彈出來。
1、建立一個Android項目,拷貝這三張圖到 res/drawable目錄下,這三張圖用來表述按鈕的三種狀態。
2、在res/drawable目錄下建立一個android_button.xml檔案,其內容如下:
<xml version=”1.0″ encoding=”utf-8”>
<selector xmlns:android=”http://schemas.android.com/apk/res/android”>
<item android:state_pressed=”true” android:drawable=”@drawable/android_pressed” />
<item android:drawable=”@drawable/android_focused” android:state_focused=”true” />
<item android:drawable=”@drawable/android_normal” />
</selector>
注意,xml中的三個item之間是有嚴格循序關聯性的,只有前兩個不為真時才會選擇第三個item,如果第三個放在了第一位,那麼後面兩個定義了也是白定義,你不信可以換一下順序看看。
3、在main.xml中增加,下面的代碼:
view sourceprint?
1 |
<button android:layout_height= "wrap_content" android:layout_width=
"wrap_content" android:id=
"@+id/button"
android:background=
"@drawable/android_button" android:padding= "10dp" ></button> |
4、在Activity的OnCreate()中添加如下代碼:
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainCustomButton.this, “嗶,嗶,嗶!”, Toast.LENGTH_SHORT).show();
}
});
這樣點擊按鈕就會顯示”嗶,嗶,嗶!”了。是最終運行效果:
最後總結一下,使用selector自訂xml,設定button的背景屬性為這個自訂xml即可實現不同狀態換不同的映像。