Android UI Layout 之 AbsoluteLayout
2011-04-01 09:14
351 查看
在 Android UI 中,最基本的构建单位(building block)是 android.view.View。一个 View 占据屏幕上的一个矩形区域,并负责该区域的绘画和事件处理。View 有一些子类,比如 ImageView、TextView 等可分别用来显示图像、文字…… View 还有一个特殊的子类 ViewGroup,ViewGroup 在 UI layout 中充当“容器”的角色,用以“包含”其他 View 以及 ViewGroup:
viewgroup.png由于 ViewGroup 是一个 abstract class 无法直接实例化,所以在 layout 中真正充当“容器”角色的应该是 ViewGroup 的子类 :AbsoluteLayout、 FrameLayout、 LinearLayout、 RelativeLayout 等。在实际的 UI 编程中,使用不同的 Layout 类作为容器,对该容器中的各个子 View 的排列方式有很大影响。比如,LinearLayout 中的各个子 View 按照横向或者纵向线性排列;而 AbsoluteLayout 中各个子 View 可以指定以像素为单位的“绝对”位置。AbsoluteLayout 的这种“绝对”定位的布局方式和我们非常熟悉的 Windows 编程中的 SetWindowPos() 或 Form1.Left = 10 的布局方式是一样的,比较简单:
现在我们新建一个 Android 工程中,在其主 Activity 类中添加如下三个成员:
private AbsoluteLayout al;
private TextView tv;
private View v;
改写这个类的 onCreate 方法如下:
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
构造一个 AbsoluteLayout,设置其背景色
al = new AbsoluteLayout(this);
al.setBackgroundColor(Color.YELLOW);
构造一个 TextView 并设置其 text 和 背景色
tv = new TextView(this);
tv.setText("Android is a software stack for mobile devices that includes an operating system, middleware and key applications. ");
tv.setBackgroundColor(Color.BLUE);
用该 View 在父 View 中的 width,height,x,y 作为参数构造一个 AbsoluteLayout.LayoutParams
AbsoluteLayout.LayoutParams tvLP = new AbsoluteLayout.LayoutParams(70, 50, 10, 20);
把这个 TextView 加入到 AbsoluteLayout 中,并应用上一步创建的 LayoutParams。这样 TextView 就会显示在我们指定的位置上了。
al.addView(tv, tvLP);
v = new View(this);
v.setBackgroundColor(Color.RED);
AbsoluteLayout.LayoutParams vLP = new AbsoluteLayout.LayoutParams(70, 50, 90, 70);
也可以先为子 View 设置 LayoutParams,然后再调用一个参数的 ViewGroup.addView(View) 来添加。效果是一样的。
v.setLayoutParams(vLP);
al.addView(v);
设置 al 为本 Activity 的 content
这样,在该 Activity 被调用时,就会显示该 AbsoluteLayout 和其子 View
this.setContentView(al);
}
相关文章推荐
- Android UI Layout 之 AbsoluteLayout
- android 动态UI Layout 之 RelativeLayout用法
- Android UI LinearLayout权限级别与TableLayout混合使用,
- Android之LinearLayout、AbsoluteLayout
- Android UI开发详解之Layout_gravity和gravity的区别
- Android UI 优化 [ 类别:Layout ] #1
- Android:UI控件DrawerLayout、Fragment、SlidingLayout、侧滑菜单 推荐
- Android UI控件系列:LinearLayout(线性布局)
- Android入门第二篇之LinearLayout、AbsoluteLayout
- AndroidのUI布局之layout weight
- 【UI布局】浅谈android五大布局-FrameLayout、LinearLayout、AbsoluteLayout、RelativeLayout、TableLayout】
- Android UI 优化 [ 类别:Layout ] #2
- Android UI 优化 [ 类别:Layout ] #3 merge用法 -android
- Android UI控件系列:RelativeLayout(相对布局)
- android-UI学习之RelativeLayout
- Android实习收获:UI细节bug引发的layout_weight深入理解
- Android UI 优化 [ 类别:Layout ] <merge>的学习
- Android开源库V - Layout:淘宝、天猫UI开源框架收藏分享
- Android UI RelativeLayout相对布局
- Android中利用LinearLayout动态添加UI控件