A layout defines the structure for a user interface in your app, such as in an activity.All elements in the layout are built using a hierarchy of View andViewGroup objects. A View usuallydraws something the user can see and interact with. Whereas a ViewGroup is aninvisible container that defines the layout structure for View và otherViewGroup objects, as shown in figure 1.
Bạn đang xem: Lập trình android
Figure 1. Illustration of a view hierarchy, which defines aUI layout
The View objects are usually called "widgets" và can be one of manysubclasses, such as Button or TextView. TheViewGroup objects are usually called "layouts" can be one of many types thatprovide a different layout structure, such as LinearLayout orConstraintLayout.
You can declare a layout in two ways:Instantiate layout elements at runtime. Yourphầm mềm can create View and ViewGroup objects (và manipulate their properties) programmatically.
Declaring your UI in XML allows you to lớn separate the presentation of your tiện ích from the code thatcontrols its behavior. Using XML files also makes it easy to lớn provide different layouts fordifferent screen sizes and orientations (discussed further in Supporting Different Screen Sizes).
The shrinkingthecamel.com framework gives you the flexibility to lớn use either or both of these methods tobuild your app"s UI. For example, you can declare your app"s mặc định layouts in XML, and thenmodify the layout at runtime.
Tip:To debug your layout at runtime, use theLayout Inspector tool.
Write the XML
Using shrinkingthecamel.com"s XML vocabulary, you can quickly kiến thiết UI layouts và the screen elements they contain, in the same way you create web pages in HTML — with a series of nested elements.
Each layout tệp tin must contain exactly one root element, which must be a View or ViewGroup object. Once you"ve defined the root element, you can add additional layout objects or widgets as child elements to gradually build a View hierarchy that defines your layout. For example, here"s an XML layout that uses a vertical LinearLayoutto hold a TextView & a Button:
After you"ve declared your layout in XML, save the tệp tin with the .xml extension,in your shrinkingthecamel.com project"s res/layout/ directory, so it will properly compile.
More information about the syntax for a layout XML file is available in the Layout Resources document.
Load the XML Resource
When you compile your ứng dụng, each XML layout file is compiled into aView resource. You should load the layout resource from your ứng dụng code, in yourActivity.onCreate() callback implementation.Do so by calling setContentView(),passing it the reference to your layout resource in the khung of:R.layout.layout_file_name.For example, if your XML layout is saved as main_layout.xml, you would load itfor your Activity like so:
fun onCreate(savedInstanceState: Bundle) super.onCreate(savedInstanceState) setContentView(R.layout.main_layout)
Javapublic void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); setContentView(R.layout.main_layout);
The onCreate() callbaông chồng method in your Activity is called by the shrinkingthecamel.com framework whenyour Activity is launched (see the discussion about lifecycles, in theActivitiesdocument).
Every View & ViewGroup object supports their own variety of XML attributes.Some attributes are specific to a View object (for example, TextView supports the textSizeattribute), but these attributes are also inherited by any View objects that may extend this class.Some are common khổng lồ all View objects, because they are inherited from the root View class (likethe id attribute). And, other attributes are considered "layout parameters," which areattributes that describe certain layout orientations of the View object, as defined by that object"sparent ViewGroup object.
Any View object may have sầu an integer ID associated with it, khổng lồ uniquely identify the View within the tree.When the ứng dụng is compiled, this ID is referenced as an integer, but the ID is typicallyassigned in the layout XML file as a string, in the id attribute.This is an XML attribute common lớn all View objects(defined by the View class) & you will use it very often.The syntax for an ID, inside an XML tag is:
) at the beginning of the string indicates that the XML parser should parse & expand the restof the ID string và identify it as an ID resource. The plus-symbol (+) means that this is a new resource name that mustbe created & added to our resources (in the R.java file). There are a number of other ID resources thatare offered by the shrinkingthecamel.com framework. When referencing an shrinkingthecamel.com resource ID, you bởi vì not need the plus-symbol,but must add the app shrinkingthecamel.com package namespace, like so:
shrinkingthecamel.com:id/empty"With the app shrinkingthecamel.com package namespace in place, we"re now referencing an ID from the apk.Rresources class, rather than the local resources class.
In order lớn create views và reference them from the tiện ích, a common pattern is to:Define a view/widget in the layout file and assign it a unique ID:
Defining IDs for view objects is important when creating a RelativeLayout.In a relative layout, sibling views can define their layout relative khổng lồ another sibling view,which is referenced by the unique ID.
An ID need not be quality throughout the entire tree, but it should bechất lượng within the part of the tree you are searching (which may often be the entire tree, so it"s bestkhổng lồ be completely chất lượng when possible).
Note: With shrinkingthecamel.com Studio 3.6 và higher, theview binding feature can replacefindViewById() calls & provides compile-time type safety forcode that interacts with views. Consider using view binding instead offindViewById().
XML layout attributes named layout_something definelayout parameters for the View that are appropriate for the ViewGroup in which it resides.
Every ViewGroup class implements a nested class that extends ViewGroup.LayoutParams. This subclasscontains property types that define the kích cỡ và position for each child view, asappropriate for the view group. As you can see in figure 2, the parentview group defines layout parameters for each child view (including the child view group).
Figure 2. Visualization of a view hierarchy with layoutparameters associated with each view
chú ý that every LayoutParams subclass has its own syntax for settingvalues. Each child element must define LayoutParams that are appropriate for its parent,though it may also define different LayoutParams for its own children.
All view groups include a width and height (layout_width andlayout_height), and each view is required khổng lồ define them. ManyLayoutParams also include optional margins and borders. You can specify width and height with exact measurements, though you probablywon"t want to vì this often. More often, you will use one of these constants tophối the width or height:wrap_nội dung tells your view to kích cỡ itself to the dimensionsrequired by its nội dung. match_parenttells your view to become as big as its parent view group will allow.
In general, specifying a layout width & height using absolute units such aspixels is not recommended. Instead, using relative sầu measurements such asdensity-independent px units (dp), wrap_content, ormatch_parent, is a better approach, because it helps ensure thatyour ứng dụng will display properly across a variety of device screen sizes.The accepted measurement types are defined in theAvailable Resources document.
The geometry of a view is that of a rectangle. A view has a location, expressed as a pair of left and top coordinates, và two dimensions, expressed as a width và a height. The unit for location and dimensions is the px.
It is possible lớn retrieve sầu the location of a view by invoking the methods getLeft() và getTop(). The former returns the left, or X, coordinate of the rectangle representing the view. The latter returns the top, or Y, coordinate of the rectangle representing the view. These methods both return the location of the view relative sầu lớn its parent. For instance, when getLeft() returns đôi mươi, that means the view is located đôi mươi pixels to the right of the left edge of its direct parent.
In addition, several convenience methods are offered khổng lồ avoid unnecessary computations, namely getRight() and getBottom(). These methods return the coordinates of the right & bottom edges of the rectangle representing the view. For instance, calling getRight() is similar khổng lồ the following computation: getLeft() + getWidth().
Size, Padding & Margins
The kích thước of a view is expressed with a width & a height. A view actually possesses two pairs of width and height values.
The first pair is known as measured width & measured height. These dimensions define how big a view wants lớn be within its parent. The measured dimensions can be obtained by calling getMeasuredWidth() & getMeasuredHeight().
The second pair is simply known as width & height, or sometimes drawing width & drawing height. These dimensions define the actual kích cỡ of the view on screen, at drawing time & after layout. These values may, but bởi vì not have sầu khổng lồ, be different from the measured width & height. The width và height can be obtained by calling getWidth() and getHeight().
To measure its dimensions, a view takes into tài khoản its padding. The padding is expressed in pixels for the left, top, right and bottom parts of the view. Padding can be used to lớn offphối the content of the view by a specific number of pixels. For instance, a left padding of 2 will push the view"s nội dung by 2 pixels lớn the right of the left edge. Padding can be phối using the setPadding(int, int, int, int) method và queried by calling getPaddingLeft(), getPaddingTop(), getPaddingRight() & getPaddingBottom().
Even though a view can define a padding, it does not provide any support for margins. However, view groups provide such a tư vấn. Refer to lớn ViewGroup and ViewGroup.MarginLayoutParams for further information.
For more information about dimensions, see Dimension Values.
Each subclass of the ViewGroup class provides a chất lượng way to displaythe views you nest within it. Below are some of the more common layout types that are builtinto the shrinkingthecamel.com platform.
Note: Although you can nest one or more layouts within anotherlayout khổng lồ achieve your UI thiết kế, you should strive to lớn keep your layout hierarchy as shallow aspossible. Your layout draws faster if it has fewer nested layouts (a wide view hierarchy isbetter than a deep view hierarchy).