Android 自学之绝对布局 AbsoluteLayout

绝对布局(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     @Override
17     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中一般支持如下常用的距离单位:

  1. px(像素):每一个像素对应屏幕上的一个点。
  2. dip或dp(device independent pixels,设备独立像素):一种基于屏幕密度的抽象单位。例如:在每英寸160点显示器上,1dip=1px。但随着屏幕密度的改变,dip与px的换算会发生改变。
  3. sp(scaled pixels,比例像素):主要处理字体大小,可以根据用户的字体大小首选项进行缩放。
  4. in(英寸):标准长度单位。
  5. mm(毫米):标准长度单位。
  6. pt(磅):标准长度单位,1/72英寸。
原文地址:https://www.cnblogs.com/Yang-jing/p/3747124.html