標籤:android style c class blog code
絕對布局(AbsoluteLayout),絕對布局就像java AWT中的空布局;所謂的絕對布局就是Android不提供任何的布局控制,而是有開發人員自己通過X座標和Y座標來控制組件的位置。當使用絕對布局作為版面配置容器的時候,版面配置容器不在管理子容器的位置,大小(這些都需要開發人員自己控制)。
在使用絕對布局的時,每個組件都可以使用這兩個XML屬性
layout_x:指定該子組件的X座標;
layout_y:指定該子組件的Y座標;
以一個學習的例子做範例:
layout/main.xml
1 <?xml version="1.0" encoding="utf-8"?> 2 <AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:orientation="vertical" 4 android:layout_width="fill_parent" 5 android:layout_height="fill_parent" 6 > 7 <!-- 定義一個文字框,使用絕對位置 --> 8 <TextView 9 android:layout_x="20dip"10 android:layout_y="20dip"11 android:layout_width="wrap_content" 12 android:layout_height="wrap_content" 13 android:text="使用者名稱:"14 />15 <!-- 定義一個文本編輯框,使用絕對位置 -->16 <EditText 17 android:layout_x="80dip"18 android:layout_y="15dip"19 android:layout_width="wrap_content" 20 android:width="200px" 21 android:layout_height="wrap_content" 22 />23 <!-- 定義一個文字框,使用絕對位置 --> 24 <TextView 25 android:layout_x="20dip"26 android:layout_y="80dip"27 android:layout_width="wrap_content" 28 android:layout_height="wrap_content" 29 android:text="密 碼:"30 />31 <!-- 定義一個文本編輯框,使用絕對位置 --> 32 <EditText 33 android:layout_x="80dip"34 android:layout_y="75dip"35 android:layout_width="wrap_content" 36 android:width="200px" 37 android:layout_height="wrap_content" 38 android:password="true"39 />40 <!-- 定義一個按鈕,使用絕對位置 -->41 <Button 42 android:layout_x="130dip"43 android:layout_y="135dip"44 android:layout_width="wrap_content" 45 android:layout_height="wrap_content" 46 android:text="登 錄"47 /> 48 </AbsoluteLayout>
上面代碼所展示的:
主程式
com.example.absolutelayouttest.MainActivity.java
1 package com.example.absolutelayouttest; 2 3 import android.support.v7.app.ActionBarActivity; 4 import android.support.v7.app.ActionBar; 5 import android.support.v4.app.Fragment; 6 import android.os.Bundle; 7 import android.view.LayoutInflater; 8 import android.view.Menu; 9 import android.view.MenuItem;10 import android.view.View;11 import android.view.ViewGroup;12 import android.os.Build;13 14 public class MainActivity extends ActionBarActivity {15 16 @Override17 protected void onCreate(Bundle savedInstanceState) {18 super.onCreate(savedInstanceState);19 setContentView(R.layout.main);20 21 22 }23 24 }
上面的主程式就只是把layout/main.xml布局顯示了一下。
layout/main.xml介面布局中指定的各組件android:layout_x、android:layout_y屬性時指定了形如20dip的屬性值。
Android中一般支援如下常用的距離單位:
- px(像素):每一個像素對應螢幕上的一個點。
- dip或dp(device independent pixels,裝置獨立像素):一種基於螢幕密度的抽象單位。例如:在每英寸160點顯示器上,1dip=1px。但隨著螢幕密度的改變,dip與px的換算會發生改變。
- sp(scaled pixels,比例像素):主要處理字型大小,可以根據使用者的字型大小喜好設定進行縮放。
- in(英寸):標準長度單位。
- mm(毫米):標準長度單位。
- pt(磅):標準長度單位,1/72英寸。