Android View and ViewGroup

2019-06-16 06:37发布

In Android ViewGroup inherits from View. A ViewGroup is a container which holds Views.

ViewGroup (LinearLayout)
View (TextView)

Why did folks at Android defined this relationship as Inheritance instead of composition. As the ViewGroup contains Views shouldn't it be composition ?

6条回答
别忘想泡老子
2楼-- · 2019-06-16 07:06

I think you're getting too hung up on the wording.

A "ViewGroup" has every bit as much reason to inherit from a "View" as a "TextView", and "ImageView" or ... more to the point ... a "ScrollView" or a "SurfaceView" (the latter two both "contain things").

Perhaps "View" wasn't necessarily the best choice of terms ... but the class heirarchy makes complete sense. Regardless of what it's subclasses are named :)

IMHO ...

查看更多
啃猪蹄的小仙女
3楼-- · 2019-06-16 07:08

I think this is a great example of the Composite design pattern:

http://en.wikipedia.org/wiki/Composite_pattern

Even though the naming might not be the best...

查看更多
爷的心禁止访问
4楼-- · 2019-06-16 07:08

A ViewGroup is a special view that can contain other views. - The view group is the base class for layouts and views containers - For example, RelativeLayout is the ViewGroup that contains TextView(View), and other Layouts also.

refer link for info: https://developer.android.com/reference/android/view/ViewGroup.html

A View represents the basic building block for user interface components -It occupies rectangle on the screen and is responsible for drawing and handling events. - Examples are EditText, Button, TextView etc

refer link for info: https://developer.android.com/reference/android/view/View.html

查看更多
可以哭但决不认输i
5楼-- · 2019-06-16 07:23

Reading the official doc is the golden rule.

A ViewGroup is a special view that can contain other views (called children.) The view group is the base class for layouts and views containers. This class also defines the ViewGroup.LayoutParams class which serves as the base class for layouts parameters.


If you still do not find out what it is, search with Google image:

enter image description here

查看更多
Explosion°爆炸
6楼-- · 2019-06-16 07:27

A ViewGroup is a (subclass of) View because it can serve as a view in important ways:

  • It can be an element in a layout XML file
  • It can be displayed on the screen (by displaying its child views, its own background color, etc.)
  • It gets inflated along with the rest of the view hierarchy
  • It can serve as an activity's content view (via setContentView())

So it really is a View.

I agree that the classname ViewGroup is a bit confusing, because it sounds like it's a group, not a view. Calling it ViewGroupView might have been more logical, if unwieldy.

查看更多
相关推荐>>
7楼-- · 2019-06-16 07:28

Viewgroup inherits properties of views and does more with other views and viewgroup

查看更多
登录 后发表回答