Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android View and ViewGroup

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 ?

like image 465
Vinoth Avatar asked Dec 23 '11 06:12

Vinoth


People also ask

What is android ViewGroup?

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.

Is layout a ViewGroup?

The View objects are usually called "widgets" and can be one of many subclasses, such as Button or TextView . The ViewGroup objects are usually called "layouts" can be one of many types that provide a different layout structure, such as LinearLayout or ConstraintLayout .

What are view and ViewGroup classes in android why layouts are created using XML file?

A ViewGroup act as a base class for layouts and layouts parameters that hold other Views or ViewGroups and to define the layout properties. They are Generally Called layouts. The Android framework will allow us to use UI elements or widgets in two ways: Use UI elements in the XML file.


1 Answers

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.

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).

like image 192
LarsH Avatar answered Oct 21 '22 00:10

LarsH