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 ?
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 ...
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...
A ViewGroup
is a (subclass of) View
because it can serve as a view in important ways:
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.
Why did folks at Android define this relationship as Inheritance instead of composition? As the ViewGroup contains Views shouldn't it be composition?
In a case like this, inheritance and composition are not mutually exclusive. A ViewGroup is a View (inheritance) and a ViewGroup can contain Views (composition).
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:
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
视图组继承视图的属性,并与其他视图和视图组做更多的事情
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.