技术笔记:Layouts

简介: 技术笔记:Layouts

Layouts


In this document 在这个文档


Write the XML 写XML文件


Load the XML Resource 加载xml资源


Attributes 属性


ID  Id


Layout Parameters 布局参数


Layout Position  布局位置


Size, Padding and Margins  大小,内部空隙,外部空隙


Common Layouts  常用的布局


Building Layouts with an Adapter 用适配器创建布局


Filling an adapter view with data  用数据填充适配器视图


Handling click events  处理单击事件


Key classes关键类


View  


ViewGroup


ViewGroup.LayoutParams


See also


Building a Simple User Interface创建一个简单的用户交互界面


A layout defines the visual structure for a user interface, such as the UI for an activity or app widget. You can declare a layout in two ways:


Declare UI elements in XML. Android provides a straightforward XML vocabulary that corresponds to the View classes and subclasses, such as those for widgets and layouts.


Instantiate layout elements at runtime. Your application can create View and ViewGroup objects (and manipulate their properties) programmatically.


一个布局为用户交互接口定义了可视化的结构,例如一个activity或者应用组件的UI。你可以用如下两种方式的一种声明一个布局:


  1.在XM中声明UI元素。 Android提供了直接的XML词汇,这些词汇对应于View各种类和View的各种子类对应。例如一些组件和布局。


  2.在运行时,实例化布局元素。你的应用可以通过编码的方式创建View和ViewGroup对象(并且指定它们的属性)。


The Android framework gives you the flexibility to use either or both of these methods for declaring and managing your application's UI. For example, you could declare your application's default layouts in XML, including the screen elements that will appear in them and their properties. You could then add code in your application that would modify the state of the screen objects, including those declared in XML, at run time.


The ADT Plugin for Eclipse offers a layout preview of your XML — with the XML file opened, select the Layout tab.


You should also try the Hierarchy Viewer tool, for debugging layouts — it reveals layout property values, draws wireframes with padding/margin indicators, and full rendered views while you debug on the emulator or device.


The layoutopt tool lets you quickly analyze your layouts and hierarchies for inefficiencies or other problems.


Android框架让你可以灵活的使用其中的一个或者两个方法去声明和管理你的应用程序的UI。例如,你可以在XML文件中声明默认的布局,包括默认布局中包含的屏幕元素以及它们的属性。你可以然后在应用程序中通过编码的方式动态修改屏幕对象的状态,包括在XML中声明的状态。


  1.ADT_Plugin_for_Eclipse提供了预览你的XML文件布局的方式——当XML打开时,选择Layout标签。


  2.你也可以尝试使用Hierarchy View工具,用它来调试布局——它揭露了布局属性值,画出了线框并标有padding/margin值得指示标志,并且在模拟器或者设备上的View。


  3.layoutopt工具让你可以快速的分析你的布局和层级中无效问题或者其他问题。


The advantage to declaring your UI in XML is that it enables you to better separate the presentation of your application from the code that controls its behavior. Your UI descriptions are external to your application code, which means that you can modify or adapt it without having to modify your source code and recompile. For example, you can create XML layouts for different screen orientations, different device screen sizes, and different languages. Additionally, declaring the layout in XML makes it easier to visualize the structure of your UI, so it's easier to debug problems. As such, this document focuses on teaching you how to declare your layout in XML. If you're interested in instantiating View objects at runtime, refer to the ViewGroup and View class references.


在XML 文件中声明的UI的优势是 这样做可以让你更好地把应用的展现和控制应用行为的代码分离。你的UI描述是对你的应用程序代码的一种扩展,也就是说你可以修改或者调整它而不需要修改你的源代码和重新编译。例如,你可以为不同的屏幕方向、设备屏幕大小、不同的语言创建不同的XML布局。而且,在XML文件中声明布局可以更容易让你的UI结构可视化,因此也容易调试出问题。鉴于这些原因,这篇文档关注于教你如何在XML文件中声明你的布局。如果你对在运行时实例化View对象感兴趣,请看ViewGroup类和View类的参考手册。


In general, the XML vocabulary for declaring UI elements closely follows the structure and naming of the classes and methods, where element names correspond to class names and attribute names correspond to methods. In fact, the correspondence is often so direct that you can guess what XML attribute corresponds to a class method, or guess what class corresponds to a given xml element. However, note that not all vocabulary is identical. In some cases, there are slight naming differences. For example, the EditText element has a text attribute that corresponds to EditText.setText().


一般来说,XML中声明UI元素的词汇遵循类和方法的结构和名字,元素名对应类名。属性名对应方法。实际上,这种对应通常是直接的以至于让你可以猜到什么XML属性对应一个类的方法,或者猜到什么类对应于一个给定的XML元素。然而,不是所有词汇是完全相同的。在一些情况下,存在稍微的名字差别。例如,EditText元素有一个text属性,它对应的方法是EditText.setText()。


Tip: Learn more about different layout types in Common Layout Objects. There are also a collection of tutorials on building various layouts in the Hello Views tutorial guide.


小提示:学习更多不同的参数类型,请看Common Layout Objects部分。在Hello View学习指南中,也有一些创建不同布局的学习指南。


Write the XML书写XML


Using Android's XML vocabulary, you can quickly design UI layouts and the screen elements they contain, in the same way you create web pages in HTML — with a series of nested elements.


使用android的XML词汇,你可以快速的设计UI布局和布局中包含的屏幕元素,与你在HTML中创建web页面的方式相同。都有一些内在的元素。


Each layout file 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 LinearLayout to hold a TextView and a Button:


<?xml version="1.0" encoding="utf-8"?>="fill_parent" android:layout_Height</span>="fill_parent" android:orientation="vertical"="wrap_content" android:layout_Height</span>="wrap_content" android:text="Hello, I am a TextView"/> ="wrap_content" android:layout_Height</span>="wrap_content" android:text="Hello, I am a Button"/>


After you've declared your layout in XML, save the file with the .xml extension, in your Android project's res/layout/ directory, so it will properly compile.


每个布局文件必须包含且仅包含一个根元素。这个根元素可以是一个View或者ViewGroup对象。一旦你定义了根元素,你可以添加额外的布局对象或者组件作为根元素的子元素。渐渐的,就可以构造出view层级出来,也即确定了你的布局。例如,下面是一个XML布局。它使用垂直的线性布局去hold一个TextView和一个Button。


More information about the syntax for a layout XML file is available in the Layout Resources document.


更多关于XML文件布局语法的信息请见Layout Resource 这篇文章。


Load the XML Resource加载XML资源


When you compile your application, each XML layout file is compiled into a View resource. You should load the layout resource from your application code, in your Activity.onCreate() callback implementation. Do so by calling setContentView(), passing it the reference to your layout resource in the form of: R.layout.layout_file_name For example, if your XML layout is saved as main_layout.xml, you would load it for your Activity like so:


publicvoid onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main_layout);}


The onCreate() callback method in your Activity is called by the Android framework when your Activity is launched (see the discussion about lifecycles, in the Activities document).


当你编译你的应用时,每一个XML布局文件会被编译成一个View资源。你需要在你的应用程序编码中加载布局资源,在Activity.onCreate()回调方法中实现加载。加载通过调用setContentView(资源索引)的方式实现。布局资源的索引形式为:R.layout.layout_file_name。例如,你的XML布局文件保存的名字为main_layout.xml,在你的acitivity中加载它的方式如下:


publicvoid onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main_layout);}


在你的Activity中的这个onCreate()回调方法是在Activity启动的时候被Android框架调用的(请见Acitivity文档中的生命周期)。


Attributes属性


Every View and ViewGroup object supports their own variety of XML attributes. Some attributes are specific to a View object (for example, TextView supports the textSize attribute), but these attributes are also inherited by any View objects that may extend this class. Some are common to all View objects, because they are inherited from the root View class (like the id attribute). And, other attributes are considered "layout parameters," which are attributes that describe certain layout orientations of the View object, as defined by that object's parent ViewGroup object.


每个View和ViewGroup对象支持他们自己的XML属性。这些属性特定到一个View对象(例如,TextView支持textSize属性),但是这些属性也会被这个类的任一子类继承。有些属性是对所有的View对象通用的,因为它们都继承自根View类(像id属性)。有些属性被视作为“布局属性”。布局属性描述特定布局方向以确定布局里面的view对象的排列方向。布局属性是由一个对象的父ViewGroup定义的。


ID


Any View object may have an integer ID associated with it, to uniquely identify the View within the tree. When the application is compiled, this ID is referenced as an integer, but the ID is typically assigned in the layout XML file as a string, in the id attribute. This is an XML attribute common to all View objects (defined by the View class) and you will use it very often. The syntax for an ID, inside an XML tag is:


android:id="@+id/my_button"


任何View对象可以关联一个整形ID,用来确定树里面View的唯一性。当这个应用被编译的时候,这个ID被视为一个整数,尽管这个ID在XML布局文件中是被指定为一个字符串的形式。这个XML属性是所有View对象(通过View类定义)通用的。你可以经常使用ID。对于一个ID的语法,在XML中的标签,它是这样的:


android:id="@+id/my_button"


The at-symbol (@) at the beginning of the string indicates that the XML parser should parse and expand the rest of the ID string and identify it as an ID resource. The plus-symbol (+) means that this is a new resource name that must be created and added to our resources (in the R.java file). There are a number of other ID resources that are offered by the Android framework. When referencing an Android resource ID, you do not need the plus-symbol, but must add the android package namespace, like so:


android:id="@android:id/empty"


With the android package namespace in place, we're now referencing an ID from the android.R resources class, rather than the local resources class.


这个在字符串开始地方的at标记符@表明XML解析器应该解析并且展开剩余的ID字符串并且将它作为一个ID资源。这个+标识意味着这是一个新的资源名,这个新的资源名必须被创建而且加入到我们的资源文件(R.java)中。还有很多其他的由Android framework提供的ID资源。当引用一个Android的资源ID时,你不需要添加+标识,但是必须添加android包的命名空间,例如“android:id=@android:id/empty”.使用android包的命名空间,我们现在引用android.R资源类中的一个ID,而不需要本地资源类。


In order to create views and reference them from the application, a common pattern is to:


Define a view/widget in the layout file and assign it a unique ID:


="wrap_content" android:layout_Height</span>="wrap_content" android:text="@string/my_button_text"/>


Then create an instance of the view object and capture it from the layout (typically in the onCreate() method):


Button myButton =(Button) findViewById(R.id.my_button);


Defining IDs for view objects is important when creating a RelativeLayout. In a relative layout, sibling views can define their layout relative to another sibling view, which is referenced by the unique ID.


An ID need not be unique throughout the entire tree, but it should be unique within the part of the tree you are searching (which may often be the entire tree, so it's best to be completely unique when possible).


为了创建Views和从应用程序中引用这些Views,一个常用的模式如下:


1.在布局文件中定义一个view/widget并赋予它一个独特的ID:


="wrap_content" android:layout_Height</span>="wrap_content" android:text="@string/my_button_text"/>


2.然后创建view对象的一个实例并从布局中捕捉到它(通常在onCreate()方法中):


Button myButton =(Button) findViewById(R.id.my_button);


当创建一个相对布局时,为view对象些创建IDS是很重要的。在一个相对布局中,兄弟view可以定义相对于其他兄弟view的相对布局,这样就需要引用View独特的ID。


一个ID不需要是独特的在整个树中,但它必须在你所寻找的局部树中独特。然而通常都是在整个树中进行查找,所以最好可能的话就让view的ID是全局树中是独特的。


Layout Parameters布局参数


XML layout attributes named layout_something define layout parameters for the View that are appropriate for the ViewGroup in which it resides.


XML布局属性命名为layout_something。XML布局属性为View定义了布局参数,使View在View所居住的ViewGroup中能够合适的布局。


Every ViewGroup class implements a nested class that extends ViewGroup.LayoutParams. This subclass contains property types that define the size and position for each child view, as appropriate for the view group. As you can see in figure 1, the parent view group defines layout parameters for each child view (including the child view group).


每一个ViewGroup实现了一个内部类。这个内部类继承自ViewGroup.LayoutParams。这个子类包含了一些属性类型,包括定义每个子View大小和位置,对于view group来说合适的属性。正如你在图1看到的,父 view group为每个子view(包括view group)定义了布局参数。


Figure 1. Visualization of a view hierarchy with layout parameters associated with each view.


view层级的可视化并伴有每个view所关联的布局参数


Note that every LayoutParams subclass has its own syntax for setting values. 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</code> and layout_Height</code>), and each view is required to define them. Many LayoutParams also include optional margins and borders.


所有的view groups包含一个宽和一个高属性(layout_widht和layout_height),并且每个view也被要求定义宽和高属性。很多布局参数也包括可选的margins和borders。


You can specify width and height with exact measurements, though you probably won't want to do this often. More often, you will use one of these constants to set the width or height:


wrap_content tells your view to size itself to the dimensions required by its content


fill_parent (renamed match_parent in API Level 8) tells your view to become as big as its parent view group will allow.


你可以用指定的精确的参数指定宽度和高度,即使你或许不想经常这样做。更常用的情况是,你会使用下面元素常量中的一两个来设置宽度和高度:


wrap_content 告诉元素view根据自身内容调整元素大小


fill_parent (在API 8 版本中,重新命名为match_parent)告诉元素view 尽可能的有它的父 view group允许的大小那样大


In general, specifying a layout width and height using absolute units such as pixels is not recommended. Instead, using relative measurements such as density-independent pixel units (dp), wrap_content, or fill_parent, is a better approach, because it helps ensure that your application will display properly across a variety of device screen sizes. The accepted measurement types are defined in the Available Resources document.


一般来说,使用绝对的单元例如pixels来指定一个布局的宽度和高度是不被推荐的。取而代之,使用相对的参数例如独立的密度像素 density-independent pixel单元(dp),wrap_content,或者fill_parent是更好的方式,因为它使你的应用在各种不同的屏幕尺寸设备上会合适的显示出来。可被接受的度量类型在Available Resources文档中定义。


Layout Position布局定位


The geometry of a view is that of a rectangle. A view has a location, expressed as a pair of left and top coordinates, and two dimensions, expressed as a width and a height. The unit for location and dimensions is the pixel.


一个view的几何形状是一个矩形。一个view有一个位置,通过左上坐标和两个大小来表示。两个大小分别为宽和高。位置和大小的衡量单元是pixel。


It is possible to retrieve the location of a view by invoking the methods getLeft() and 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 to its parent. For instance, when getLeft() returns 20, that means the view is located 20 pixels to the right of the left edge of its direct parent.


通过调用方法getLeft()和getTop()可以获得view的位置。前一个方法view的矩阵的坐标的中left的值,即X;后者返回top的值,即Y。这些方法都是返回的是相对于它的parent的位置。例如,当getLeft()返回20,它表示这个view在它直接父亲view的左边界的右方20像素的位置。


In addition, several convenience methods are offered to avoid unnecessary computations, namely getRight() and getBottom(). These methods return the coordinates of the right and bottom edges of the rectangle representing the view. For instance, calling getRight() is similar to the following computation: getLeft() + getWidth().


//代码效果参考: http://hnjlyzjd.com/xl/wz_24813.html

而且,一些方便的方法被提供了避免不必要的计算,例如getRight()和getBottom()。这些方法返回代表这个view的矩形的右部和底部的坐标。例如,调用getRight()l类似于计算 getLeft()+getWidth().


Size, Padding and Margins大小,内边距,外边距


The size of a view is expressed with a width and a height. A view actually possess two pairs of width and height values.


一个view的大小通过宽和高来表示。一个view实际上拥有两对宽和高的值。


The first pair is known as measured Width</em> and measured Height</em>. These dimensions define how big a view wants to be within its parent. The measured dimensions can be obtained by calling getMeasuredWidth() and getMeasuredHeight().


第一对宽高值是通常知道的 标准的宽measured width 和标准的高measured height.这些像素定义了一个view想在它的父viewGroup中有多大。这个标准的大小 可以通过调用getMeasuredWidth()和getMeasuredHeight()方法获得。


The second pair is simply known as Width</em> and Height</em>, or sometimes drawing Width</em> and //代码效果参考:http://hnjlyzjd.com/hw/wz_24811.html

drawing Height</em>. These dimensions define the actual size of the view on screen, at drawing time and after layout. These values may, but do not have to, be different from the measured width and height. The width and height can be obtained by calling getWidth() and
相关文章
|
4天前
|
监控 安全 网络协议
技术笔记:TOMOYOLinux(undone)
技术笔记:TOMOYOLinux(undone)
|
4天前
|
Linux 开发工具 C++
技术笔记:RustGUI编程
技术笔记:RustGUI编程
|
4天前
|
存储 安全 数据安全/隐私保护
技术笔记:mft(转载)
技术笔记:mft(转载)
|
4天前
|
前端开发 JavaScript
技术笔记:waitFor和waitForAny的实现
技术笔记:waitFor和waitForAny的实现
|
4天前
|
自然语言处理 编译器 API
技术笔记:Roslyn介绍
技术笔记:Roslyn介绍
|
4天前
|
存储 数据库 数据安全/隐私保护
技术笔记:MouStudio技术储备之
技术笔记:MouStudio技术储备之
|
4天前
|
Linux 开发工具 C++
技术笔记:NanoGUI使用
技术笔记:NanoGUI使用
|
4天前
|
存储 JSON NoSQL
技术笔记:Stargate入门
技术笔记:Stargate入门
|
5天前
|
前端开发 关系型数据库 MySQL
技术好文:R基础学习(三)
技术好文:R基础学习(三)
|
3天前
|
数据可视化 BI OLAP
技术经验分享:DundasBI简介
技术经验分享:DundasBI简介