view 与viewGroup的关系

原文:http://www.bubuko.com/infodetail-393782.html
ViewGroup与View的关系
我们在定义一个布局时,在它的顶层通常都是使用LinearLayout或者RelativeLayout等组件来包装一些子控件,例如TextView, Button, ImageView等。例如:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    android:gravity="center" >  

    <TextView  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content"  
        android:text="@string/hello_world" />  

</RelativeLayout> 

为什么是这样呢?如果不用RelativeLayout包裹可不可以呢?、

在Android View系统分析之从setContentView说开来(一)中的ViewGroup章节中我们说了,Android中的视图树是按照如下结构来组织的,即对顶层的是一个ViewGroup,然后其子节点可以是ViewGroup、View,只有ViewGroup下能够包含子节点,View则是叶子节点。如图 :
这里写图片描述
View是屏幕上所有可见元素的根类,其中ViewGroup也是View的子类。View的官方说明如下 :

This class represents the basic building block for user interface components. A View occupies a rectangular area on the screen and is responsible for drawing and event handling. View is the base class for widgets, which are used to create interactive UI components (buttons, text fields, etc.). The ViewGroup subclass is the base class for layouts, which are invisible containers that hold other Views (or other ViewGroups) and define their layout properties.

即一个View类的对象是一个包含了一定区域的可以在屏幕上绘制、并且处理事件的UI组件,所有可以放在屏幕上显示的都是View的子类。

而ViewGroup的子类则负责这些View类型对象的布局,即规定这些View放在屏幕的哪些地方。

因此,通常情况下我们都需要使用RelativeLayout,LinearLayout等ViewGroup来组织它的子节点,以约束子View的大小、显示位置等。当然也可以不用RelativeLayout来包裹,但是这样的话布局中只可以放置一个View或者ViewGroup元素,因为没有ViewGroup的组织,布局xml中只能有一个元素。例如 : 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值