码迷,mamicode.com
首页 > 移动开发 > 详细

第三章:使用 Android Studio 编程[Learn Android Studio 汉化教程]

时间:2017-12-17 13:18:16      阅读:243      评论:0      收藏:0      [点我收藏+]

标签:固定   its   使用   reference   cat   覆盖   c中   uil   direct   

[Learn Android Studio 汉化教程]第三章:使用 Android Studio 编程

This chapter covers how to write and generate code in Android Studio. Android Studio uses its knowledge of object-oriented programming to generate extremely relevant and well-formed code. Features covered in this chapter include overriding methods, surrounding statements with Java blocks, using templates to insert code, using auto-completion, commenting code,and moving code. If your goal in reading this book is to master Android Studio, you will want to pay particularly close attention to this chapter because the tools and techniques described here in will have the greatest effect on your programming productivity.
Let’s get started. If the HelloWorld app you created in Chapter 1 is not already open, go ahead and open it now.
<翻译>本章包含如何在Android Studio中书写或生成代码。 Android Studio 使用面向对象编程的思想来生成极其相关的和格式规范的代码。本章的特色体现在重载方法,Java块的包围语句,使用模板插入代码,自动补全,注释代码和移动代码,如果你读这本书的目标是要精通Android Studio,那么你需要密切关注这章,因为所描述的工具和技术将在你的编程效率发挥最大的作用。
让我们开始吧,若是在第一章创建的 HelloWorld 应用程序还没有打开,请前往打开。

Using Code Folding
Code folding is one way of conserving screen real-estate in the Editor. Code folding allows you to hide particular blocks of code so that you can focus exclusively on those blocks that are of interest to you. If MainActivity.java is not open, open it by pressing Ctrl+N | Cmd+O and typing Main. Open the MainActivity.java class by pressing Enter, as seen in Figure 3-1.
<翻译> 使用代码折叠
代码折叠是一种在编辑器中保存屏幕实际使用空间的方式,代码折叠允许你去隐藏特定代码块以便于于你可以充分地集中注意力在你感兴趣的代码块上,如果MainActivity.java 没有打开,按Ctrl+N | Cmd+O 并输入Main,按Enter键打开MainActivity.java 的类,如图3-1

技术分享图片

Figure 3-1. Use the Enter Class Name dialog box to open MainActivity.java
<翻译>图3-1 使用输入类名对话框来打开MainActivity.java

If line numbers are not showing by default, navigate to Help ? Find Action. Type show line numbers and select the option for the Show Line Numbers Active Editor, as shown in Figure 3-2.
<翻译>如果行号默认没有显示,导航到Help ? Find,输入show line numbers并且勾选Show Line Numbers Active Editor这一项,如图3-2.

技术分享图片

Figure 3-2. Use the Enter Action or Option Name dialog box to show line numbers
<翻译>图3-2 使用输入Action或者选项名对话框来显示行号

As you observe the line numbers in MainActivity.java, you will notice something odd: the line numbers are not continuous. In Figure 3-3, the line numbers start at 1, 2, 3 and then skip to 7, 8, 9. Look carefully at line 3 in Figure 3-3. You will notice that there’s a plus symbol enclosed in a box to the left of the import statement and an ellipsis following it. If you look carefully at your own code, you will also notice that the ellipsis is highlighted in pale green.All of these visual elements are signaling you that Android Studio is hiding a block of code
that has been folded, or collapsed.
<翻译>正如你在MainActivity.java中所观察到的行号,你将会注意到一些奇怪的情况:行号不是连续的,在图3-3中,行号从1,2,3开始,然后就跳跃到7,8,9了,仔细观察图3-3的第3行,你会发现这里在import语句的左边有一个包含了“+”的方块,同时随后是省略号,如果你仔细观察你的代码,你也会注意到这个省略号用浅绿色高亮显示,这些可见的元素提示你Android Studio 正隐藏被折叠的代码块
技术分享图片

Figure 3-3. Folded block of code at the import statement
<翻译>图3-3. 在import 语句的折叠代码块

A fine dotted line called the folding outline is located along the length of the left margin,between the gray gutter and the white Editor. The folding outline can contain three icons:the plus icon enclosed in a box (as in line 3 of Figure 3-3) and the up- and down-arrows,which have horizontal lines (see lines 12 and 15 of Figure 3-3) inside them. The down-arrows indicate the beginning of a foldable block of code, whereas the up-arrows indicate the end of a foldable block of code. A plus box, as mentioned, indicates that a block of code has been folded. Clicking any of these icons toggles the corresponding block to either its folded or unfolded state. Table 3-1 contains descriptions and keyboard shortcuts for all the code-folding operations.
<翻译>位于左边留空处是折叠边框形成的细虚线,同时介于灰色留空与白色编辑器之间,折叠边框包含了三个图标:位于小方块的内部"+"号(正如图3-3的第3行)和有着水平线在里面的上下箭头,向下的将头表名是一个可折叠代码块的开始部分,同时向上箭头指示它的结束部分,上文提到的"+"号,表明某个代码块已经被折叠了,点击这些图标中的任意一个将会切换对应代码块为折叠还是打开状态,表3-1包含了代码折叠操作的描述和快捷键。
技术分享图片

Place your cursor anywhere inside the onCreate() method of MainActivity.java. Now press Ctrl+Period | Cmd+Period a few times to toggle this block expanded and collapsed. Also try using the Expand keyboard shortcut Ctrl+Numeric-Plus | Cmd+Numeric-Plus and the Collapse keyboard shortcut Ctrl+Numeric-Minus | Cmd+Numeric-Minus. 
<翻译>把你的光标放在 MainActivity.java 的onCreate() 方法中,现在长按Ctrl+Period | Cmd+Period 来切换他的代码块展开或折叠,此外,也可以用快捷键Ctrl+数字键"+"或者Cmd+数字键"+"展开代码、也可以用快捷键Ctrl+数字键"-"或者Cmd+数字键"-"折叠代码。
Finally, use your mouse to toggle blocks folded and unfolded by clicking the code-folding
icons in the folding outline. Keep in mind that folding a single block, multiple blocks, or even all the blocks in a file simply removes them from your view in order to save screen real-estate. The compiler, however, will still try to compile them when you build. Similarly, folding a block containing problematic or erroneous code will not remove any warnings or errors from the marker bar. You can change the code-folding options by selecting the menu option Settings ? Editor ? Code Folding.
<翻译>总之通过点击在折叠边框内的代码折叠图标折叠/展开你的代码块,记住,折叠单个块,多个块,或一个文件的所有块,是为了节省屏幕空间从你的视线中删除了,然而当你bulid的时候,编译器仍然会编译他们。类似的,折叠一个包含了问题的、有错误的代码的块将不会从标示条删除任何警告或者出错。你若要改变代码折叠的选项,请选择通过菜单选线进入Settings ? Editor ? Code Folding.

Performing Code Completion
<翻译>使用代码补全

Most contemporary IDEs offer some form of code completion, and Android Studio is no exception. Android Studio is always ready to help, even if you’re not actively seeking help. In practice, this means that Android Studio will suggest various options for completing your code by default as you type. The suggestion list generated by Android Studio is not always perfect, but the suggestions are ordered according to best practices, and they typically conform to proper naming conventions. Android Studio understands both the Android SDK and the Java programming language very well; in fact, it probably knows these subjects far better than you do. If you approach this tool with humility and an eagerness to learn, you will end up looking like a rock star, no matter what your former programming experience may be.
The code-completion features are context sensitive, insofar as the suggestions offered to you will be different depending on the scope of your cursor. If you’re typing code inside class scope, the code-completion suggestions will be different from those suggested to you if you were typing inside method scope. Even if you choose not to accept the code-completion suggestions, you should pay attention to them for the aforementioned reasons.
<翻译>现代大多数编译器都会提供一些代码补全的格式,Android Studio也不例外,Android Studio乐意帮助,就算你不主动去寻求帮助,实际上,Android Studio将为你各种各样的的默认提醒来随着你的输入完成你的代码。这些Android Studio自动生成的默认提醒列表可能是不完美的,但是这些提醒是根据最佳实践得到来设置的,并且它们通常遵循很好的命名规则。Android Studio可以很好地理解Android SDK和java程序设计语言;事实上,它可能知道那些问题,远远超过你所知道的,如果你以谨慎和热忱的心态学习这个工具的使用,你最终将会看起来想一个摇滚歌手,不管你的之前的编程经验是什么。
这个代码补全的特点是对上下文敏感的,在此条件下,这些补全根据你的光标所在的范围来提供给你不同的提醒,比如,你正在键入一个类范围内的代码,代码补全的提醒将是不同于你在方法范围内键入的代码,即使你选择不接受这个代码补全提醒,基于上述理由,你也需要注意他们。
Table 3-2 lists the four kinds of code completion in Android Studio:
- Default code completion occurs automatically as soon as you start typing.
- Basic code completion behaves like Default code completion but also displays a Javadoc window next to the currently selected item in the suggestion list.
- SmartType code completion also displays Javadoc but also generates a more selective and relevant suggestion list.
- Cyclic Expand Word cycles through words already used in your source document and allows you to select them.
<翻译>表3-2列出了4种在Android Studio中的代码补全:
- 一旦你键入代码,默认的代码补全功能会自动启作用
- 基本的代码补全不仅扮演着类似于默认代码补全的功能,还在提醒列表中的当前选项的旁边展示了一个Javadoc的窗口
- 精妙的代码补全同时扮演者Javadoc的功能之外,还有生成一个更敏感的相关的提醒列表
- 循环地扩展单词环,允许你选择在已用过的源代码单词
技术分享图片

Let’s start coding to demonstrate how code completion works. Right-click (Ctrl-click on Mac) on the package com.apress.gerber.helloworld and choose New ? Java Class to bring up the Create New Class dialog box, shown in Figure 3-4. Name this class Sandbox and click OK.
<翻译>让我们开始编码来演示代码补全是怎么工作的,在包com.apress.gerber.helloworld右键(Mac中是Ctrl-单击),并选择 New ? Java Class 来创建新的类对话框,如图3-4所示,吧这个类命名 Sandbox 并点击OK
技术分享图片

Figure 3-4. Create New Class dialog box
<翻译>创建新的类对话框
Inside the enclosing brackets of the Sandbox class in Sandox.java, begin to define a member by typing private Li, as shown in Figure 3-5. A code-completion menu appears with a list of possible choices for you to complete your code. Use the up- and down-arrow keys to navigate the code-completion menu. Select the option, List<E>, with your down-arrow key and press Enter.
<翻译>Sandox.java的Sandbox 类的大括号内部,定义一个私有变量,如图3-5,一个代码补全的菜单出现了,并列出了可能的选择帮你完成你的嗲吗,使用上下箭头键来导航代码补全的菜单,使用下键选择List<E>这个选项并回车。
技术分享图片

Figure 3-5. A code-completion menu appears when you start typing
<翻译>图3-5. 当你开始输入的时候出现的一个代码补全的菜单
The default behavior in Android Studio is to display the code-completion suggestion list when you start typing. You do not need to activate any keyboard shortcuts to invoke Default code completion—it happens automatically. You should now have a line of code that reads private List, as shown in Figure 3-6. Directly following the word List, type the left angle bracket (<) used for defining generics in Java. Notice that Android Studio closes the bracket clause with a closing right angle bracket and places your cursor inside the brackets.
<翻译>Android Studio的默认行为是当你开始键入时,出现代码补全提醒列表,你不需要激活任何快捷键来调用这个默认的代码补全——他是自动出现的。你应该现在有一行私有 List的代码,如图3-6,直接跟随这个单词列表,键入左尖括号用以定义在java中的泛型,注意Android Studio关闭了括号语句用封闭的右尖括号,并把你的光标置于括号中
技术分享图片

Figure 3-6. Code completion of a list with String as the generic
<翻译>图3-6. 字符串作为泛型的列表的代码补全
Type Str inside the angle brackets and press Ctrl+Space to invoke Basic code completion. You will notice that a Documentation for String Javadoc window appears next to the currently selected item (String) in the suggestion list. Scroll through the Javadoc window to see the Javadoc documentation for String. Click the up-arrow in the Javadoc window to display the detailed API documentation for String in your default browser. Return to Android Studio and select String as the generic class that you will use when defining List<String>
by pressing the Enter key.
<翻译> 在尖括号的Str类型,按下Ctrl+Space调用基本代码补全功能。你将会注意到一个String的Javadoc窗口的文档在提醒列表中出现当前选中项(String) ,滚动 Javadoc 窗口可以看到对String的Javadoc文档说明,点击向上箭头,Javadoc窗口将展示出详细的String API文档在你的默认浏览器,返回 Android Studio 并选择String 作为泛型类,你将会使用的,按Enter 键定义出List<String>。
One of the best features of Android Studio is that it suggests variable names for you. Type a space directly after private List<String> and activate Basic code completion by pressing Ctrl+Space. Android Studio generates a suggestion list, but none of the variable names is sufficiently descriptive, so type mGreetings instead. Lower-case m stands for member (a.k.a. field), and prefixing class member names with m is the naming convention in Android. Likewise, static class members are prefixed with lowercase s. You are not required to follow this naming convention, but your code will be more easily understood by others if you do. Keep in mind that local (method-scoped) variables do not follow the m and s prefix-naming convention.
Modify your line of code so that it now reads private List<String> mGreetings = new.
Invoke SmartType code completion by pressing Ctrl+Shift+Space. Select ArrayList<>() to complete this statement, including the terminating semicolon, as seen in Figure 3-7. SmartType code completion is similar to Basic code completion except that it factors in a wider scope of variables than both Default and Basic code completion when generating items in its suggestion list. For example, when using SmartType code completion on the right side of an assignment operator, the suggestion list will often include relevant factory methods.
<翻译> Android Studio的特色之一是它会为你提醒变量名,直接键入一个空格后,私有 List<String>通过按Ctr+空格出现基本的基本代码补全,Android Studio生成一个提示列表,但是上述变量名都不足于描述,因此只能键入mGreetings。小写字母m 代表成员(即域),把类的成员名用m作为前缀在Android中是一种命名约定。同样的,静态类成员用小写字母s作为前缀,你不需要遵循这种命名约定,但是你的代码会更容易被别人阅读如果你遵循了,记住局部变量(方法作用域内)不允许用m和s作为前缀约定,修改你的代码行为List<String> mGreetings = new。按 Ctrl+Shift+Space调用智能代码补全,选择ArrayList<>()完成语句,还包含了终止的分号,如图3-7,类似于基本代码补全,在生成提醒列表的时候,还比默认的和基本代码补全范围增多了,比如,当使用智能代码补全在赋值操作的右边,提醒列表通常包含了相关的工厂方法。

Note If your JDK in Android Studio is set to 7 or higher, then generated code from code-completion may use Diamond notation. For example, ArrayList<String> may appear as ArrayList<> on the right side of a declaration with assignment statements using generics, such as the one in Figure 3-7.
<翻译>注如果你的在 Android Studio 的JDK版本是7或者更高,通过代码补全的生成的代码可能是用菱形标记,比如,在使用泛型的赋值语句来定义的右边,ArrayList<String> 可能出现为ArrayList<>。
技术分享图片

Figure 3-7. SmartType code completion
<翻译>图3-7 智能代码补全

Cyclic Expand Word has a fancy name, but it’s actually very simple. Invoke Cyclic Expand Word by holding down the Alt key while pressing forward slash several times. The words offered to you are the same ones that appear in your document. As you cycle through the words, pay attention to the yellow highlighting. Now invoke Cycle Expand Word Backward by holding down the Alt and Shift keys while pressing the forward slash (question mark on Mac) several times. Notice that the offered/highlighted words now cycle down and away
from your cursor, rather than up and away.
<翻译>循环扩展词是一个花哨的名字,但是它实际上非常简单。调用循环扩展词只需按下Alt键,同时按住"/"键几秒钟,单词集合里提供你同样的单词,他们都曾出现在你的文档里,由于你的循环遍历这些单词,注意黄色高亮部分,现在调用循环扩展词,长按Alt + Shift +"/",注意到提供并高亮的单词现在向下远离你的光标,而非向上远离。

Commenting Code
<翻译>注释代码
If you’ve done any programming at all, you know that comments are lines of code that are ignored by the compiler but that contain messages or metadata that are important to coders and their collaborators. Comments may be line comments that start with two forward slashes or block comments that begin with a forward slash and an asterisk and end with an asterisk and a forward slash. From the main menu, you can activate comments by choosing Code ? Comment. However, the best way to activate comments is by using the keyboard shortcuts listed in Table 3-3.
<翻译>如果你已经完成了所有的编码工作,你了解到,有些代码行是一些注释,将会被编译器忽略,但是包含了信息或者元数据,数据是非常重要的,对于编码者和协同编码者,注释可能是行注释,以”//"开始,也可能是块注释,以"/“开始,以”/“结束,从主菜单可以看出,你可以激活注释,只需选择Code ? Comment.,然而,最好的方法是通过快捷键来截获,如表3-3所示:
技术分享图片

Type refactor initialization to constructor above the mGreetings declaration. Press Ctrl+/ | Cmd+/ to convert this text to a comment, as shown in Figure 3-7. Experiment with toggling this comment on and off by using the keyboard shortcut Ctrl+/ | Cmd+/.
<翻译>类型重构初始化被构造,并放在mGreetings 声明的上面,Ctrl+/ | Cmd+/ 把其转化为注释,如图3-7,在开启和关闭注释切换实验,只需使用快捷键Ctrl+/ | Cmd+/.
Using Code Generation
<翻译>使用代码生成
When used appropriately, code generation is the feature that will save you the most time. Code generation has the power to generate a variety of methods for you, including constructors, getters, setters, equals(), hashCode(), toString(), and so on.Before using code generation, let’s verify that Android Studio is configured properly to ignore the member name prefixes m and s. Click File ? Settings ? Code Style ? Java ? Code Generation to bring up the Settings dialog box with the Code Generation tab selected. If the Field and Static Field text boxes do not contain m and s respectively, type them there now and click Apply and then OK, as shown in Figure 3-8.
<翻译>恰当的使用代码生成功能,这一特色将为你节约大量的时间,代码生成是生成各种方法的的强大功能,包括了构造,getters, setters, equals(),hashCode(), toString(),方法等等。在你使用代码生成之前,确认Android Studio 是配置好了,可以忽略成员名称的前缀,如m和s,点击File ? Settings ? Code Style ? Java ? Code Generation将得到设置对话框,将会出现代码生成的标签页,如果域和静态域文本框不包含m和s,则键入他们并点击”应用“和”确定“,如图3-8.
技术分享图片

Figure 3-8. Adding m and s to Field and Static Field in the Code Generation tab
<翻译>图3-8 加入m和s到代码生成标签页的域和静态域
Constructors
<翻译>构造器
Place your cursor in the class scope of Sandbox.java. To generate a constructor in Android Studio, press Alt+Insert | Cmd+N and select Constructor. The Choose Fields to Initialize by Constructor dialog box, shown in Figure 3-9, enables you to select class members as parameters. We’d like a no-argument constructor, so click the Select None button.It’s common in Java to overload constructors to take different types and numbers of
parameters. You could, for example, invoke this dialog box again and generate a constructor that takes a List<String> as a parameter and assigns this parameter to our member mGreetings:List<String>.
<翻译>把你的光标放在Sandbox.java的类范围中。为了在Android Studio生成一个构造器,按Alt+Insert | Cmd+N 并选择 Constructor,那么选择的域被构造对话框初始化,如图3-9,选择类成员作为参数。我们非参数构造器,因此点击None这个按钮。在Java中,是很常见的,就是重载构造器,通过不同类型的参数和不同数量的参数,比如,你可以调用这个对话框来生成一个带List<String>参数的构造器,并且为成员变量mGreetings赋值。
技术分享图片

Figure 3-9. Choose Fields to Initialize by Constructor dialog box
<翻译> 通过构造对话框来选择要初始化的域。

Getters/Setters
<翻译>Getters/Setters
Java classes are typically encapsulated, which means that class members are most often declared as private, and the public interface to these members is provided via public accessor (getter) and public mutator (setter) methods. Click to place your cursor in the class scope of Sandbox.java and press Alt+Insert | Cmd+N. You will notice that there is one option for Getter, one for Setter, and one for both Getter and Setter. Getter and setter
methods typically come in pairs, so unless you have a good reason to omit one or the other, it’s best to generate both in one fell swoop. Select Getter and Setter from the list, as shown in Figure 3-10. In the subsequent Select Fields to Generate Getters and Setters dialog box, select mGreetings:List<String> from the list and click OK. Your class now has a getter and a setter for mGreetings, as shown in Figure 3-11. Notice that the generated code ignored the m prefix when generating the method names, because you declared m and s as prefixes in Settings earlier.
<翻译>Java类通常是封装好的,这意味着类成员通常声明为私有的,并且访问这些成员的公共接口是通过公有访问器(getter)和公有修改器(setter)方法爱提供的。在Sandbox.java类域范围内点击你的鼠标。并且按Alt+insert( Cmd + N)。你会注意到有一个选项是Getter,一个为Setter,还有Getter和Setter的组合。Getter和setter
方法一般都是成对出现的,除非你有一个很好的理由要省略其中一个或着另一个,否则最好是生成后面的组合选项。从列表中选择Getter and Setter, 如图3-10所示。在随后的选择字段生成getter和setter对话框中,从列表中选择mGreetings:List<String>列表并点击OK。你的类现在为变量mGreeting有了getter和setter,如图3-11。请注意,生成的代码忽略了m前缀,在生成方法名称的时候,因为你在之前的设置中把m和s设置为了前缀。
技术分享图片

Figure 3-10. Generating the getter and setter
<翻译> 生成访问器和修改器

技术分享图片

Figure 3-11. Generated getter and setter methods
<翻译> 生成访问器和修改器方法

Override Methods
<翻译>方法重载
Code generation understands class hierarchy, so you can override methods contained in any superclass or implemented interface. Sandbox.java is a simple Plain Old Java Object (POJO). Now you modify the Sandbox class so it extends RectShape. When you type extends RectShape, the word RectShape may be highlighted in red. If this is the case, press Alt+Enter to import the RectShape class, as shown in Figure 3-12
<翻译>代码生成是理解类继承结构的,所以你可以覆盖包含在任何父类或接口实现的方法。Sandbox.java 是一个简单的普通java对象(POJO)。现在你修改Sandbox类来继承RectShape。当你输入继承RectShape时,这个词RectShape可能以红色突出显示。如果适合你需要的情景,按Alt + Enter来导入RectShape类,如图3-12所示

技术分享图片

Figure 3-12. Extending the superclass
<翻译>继承超类

If you invoke Hierarchy View by pressing Ctrl+H, you will see the class hierarchy of Sandbox with RectShape, Shape, and Object as its ancestors, as you can see by examining Figure 3-13. Now press Alt+Insert | Cmd+N and select Override Methods. Let’s override the hasAlpha() method from Shape, as shown in Figure 3-14. The convention since version Java 5 is to annotate overridden methods with @Override, so let’s leave the Insert @Override check box selected. The @Override annotation tells the compiler to verify both the name and the signature of the method to ensure that the method is, in fact, being overridden. Modify the return statement of hasAlpha() to always return true.
<翻译>如果你通过按Ctrl+H调用了层次结构视图,您将看到带有RectShape的Sandbox的类层次结构,Shape,和Object作为它的祖先,可以通过观察图3-13,你可以明白。现在按Alt +Insert | Cmd + N并选择覆盖方法。让我们重写Shape的hasAlpha()方法,如图3 - 14所示。自java 5 版本开始的约定:要用@Override来注解想覆盖的方法,我们选中@Override复选框并插入。@Override注解告诉编译器来验证方法的名字和签名,以确保该方法事实上已被覆盖。修改hasAlpha()的返回值为true。
技术分享图片

Figure 3-13. Selecting methods to override/Implement with RectShape
<翻译>在RectShape中选择要覆盖/实现的方法

技术分享图片

Figure 3-14. Modifying the hasAlpha( ) method
<翻译>修改hasAlpha( )方法

toString( ) Method
<翻译>toString( )方法
Android Studio can generate toString() methods for you. Let’s create a toString() method for Sandbox and include the mGreetings member. Press Alt+Insert | Cmd+N and select toString(). Select your one and only member, mGreetings, and click OK. Android Studio generates a return string such as "Sandbox{" + "mGreetings=" + mGreetings + ‘}‘, as shown in Figure 3-15. If you had multiple members in our class and selected them, they too would be appended to this method’s return string. Of course, the code that is generated by toString() is not set in stone; you may change this method however you want, so long as it
returns a String.
<翻译>Android Studio 可以为你生成toString()方法。让我们为Sandbox创建一个toString()方法,同时也包括mGreetings成员。按Alt +Insert| Cmd + N并选择toString()。选择你的唯一成员——mGreetings,并单击OK。Android Studio生成一个返回字符串,如“Sandbox{“+”mGreetings = " + mGreetings +‘}’,如图3-15。如果在类中有多个成员,可选择他们,他们也会被附加到这个方法的返回字符串。当然toString()方法生成的代码并不是一成不变的,这个方法是可以改变为任何你想要的,只要它返回是一个字符串。

技术分享图片

Figure 3-15. Generate the toString( ) method
<翻译>图3-15 生成toString()方法

Delegate Methods
<翻译>委托方法
Android Studio knows about your class members and thus allows you to delegate behavior from a proxy method defined in your class to a method of your class member. That sounds complicated, but it’s easy. To show you how the Delegate Methods option works, let’s jump right into the code.
In Sandbox.java, place your cursor in class scope. Press Alt+Insert | Cmd+N and then select Delegate Methods. Select the mGreetings:List<String> and press OK. The List interface has a lot of methods to which you can delegate behavior. For simplicity, choose add(object:E):boolean, as shown in Figure 3-16. If you want to delegate multiple methods, hold down the Ctrl key (Cmd key on Mac) while selecting those methods. Click OK.
<翻译>Android Studio知道你的类成员,从而允许您从一个代理委托行为方法中定义类方法的类成员。这听起来很复杂,但它很容易。为了给你展示委托方法的选择是如何工作的,让我们转到代码中来看。在Sandbox.java,把你的光标放在类范围内。按Alt +Insert | Cmd + N,然后选择 Delegate Methods。选择mGreetings:List<String>并按下OK。列表接口有很多方法,你都可以委托行为。为简单起见,选择添加(object:E):boolean,如图3-16。如果你想委托多个方法,在选择这些方法的时候,按住Ctrl键(Cmd键在Mac),单击OK。

技术分享图片

Figure 3-16. Selecting methods to generate delegates
<翻译>选择要生成委托的方法
The generated add() method in Sandbox.java is now a proxy that delegates behavior to the add() method of the mGreetings member, as shown in Figure 3-17. Notice that the parameter to the add() method is defined as a String to match mGreetings’ generic definition, List<String>. Delegated methods are not overridden methods, so you can rename your proxy method to whatever you want, but the name add() makes perfect sense, so go ahead and leave the name as it is.
<翻译>在Sandbox.java中生成的add()方法现在是一个代理,代表mGreetings成员行为的add()方法。如图3-17所示。注意到add()方法的参数是定义为一个String来匹配mGreetings的泛型定义,List<String>。委托方法并不覆盖方法,所以您可以随意重命名你的代理方法,但这个名字add()很有意义,所以尽可能保留这个名字。

技术分享图片

Figure 3-17. Generated add( ) method
<翻译>生成 add( )方法
Inserting Live Templates
<翻译>插入动态模板
Android Studio comes with many templates that allow you to insert predefined code directly into your source files. In many IDEs, the generated code is just pasted from a template without regard to scope; however, Android Studio’s templates are scope-aware and can integrate variable data as well.
Before you start using live templates in Android Studio, let’s explore the existing live templates and create one of our own. Navigate to File ? Settings ? Live Templates. Select the Plain template group. Now click the green plus button in the upper-right corner and select Live Template. Populate the Abbreviation, Description, and Template text fields, as shown in Figure 3-18. Before this template can be applied, you must click the Define button, which looks like a blue hypertext link along the bottom of the window. Now select Java and select all the scopes (Statement, Expression, Declaration, and so on). Click Apply.
<翻译>Android Studio有很多模板,允许您将预定义的代码直接插入到你的源文件中。在许多ide,生成的代码只是从模板中粘贴,而从来不考虑作用域;但是Android Studion的模板是对作用域敏感的,也可以集成变量数据。在你开始使用Android Studion的动态模板之前,让我们探索动态模板和自定义模板。导航到File ? Settings ? Live Templates。选择普通模板组。现在在右上角单击绿色加号按钮并选择住模板。如图3-18,填充好缩写、描述和模板文本字段。在这个模板可以应用之前,您必须单击Define按钮,这看起来像一个蓝色的超文本链接,位于窗口的底部。现在选择Java和选择所有范围(语句,表达式,声明等等)。单击Apply。

技术分享图片

Figure 3-18. Create a live template called cb (comment block)
<翻译>图3-18 创建一个名为cb的动态模板(注释块)

You just created a custom live template called cb, which will be available while coding in any Java source file and in any scope. The red word $SELECTION$, shown in Figure 3-18, is a variable. You will see this variable in action shortly. The Live Template options are described in Table 3-4.
<翻译>您刚刚创建一个称为cb的自定义动态模板,将在任何Java源文件和任何范围中编码时都是可用的。如图3-18,红色的字$SELECTION$ 是一个变量。很快你会看到这个变量在起作用。动态模板的选项如表3 - 4所示
技术分享图片


Before leaving the Settings page for live templates, take a quick look at one of the existing live templates whose abbreviation is psfs, located in the Plain template group. Click psfs to inspect its contents. You will notice that this template generates a String constant with public static final String and that it is available in Java and Groovy declaration scopes only. Click OK to return to the Editor.
In the declarations section of Sandbox.java, underneath the definition of mGreetings, type psfs and then invoke live templates by pressing Ctrl+J | Cmd+J and then press Enter. Complete this statement by giving this constant a name and an assignment like so: public static final String HELLO = “Hello Sandbox”;.
<翻译>在离开动态模板的设置页面之前,浏览一下现有的动态模板,简称为psfs,在简单模板组中。单击psfs来查看其内容。你会注意到这个模板最终生成一个公共静态的字符串常量,它仅在Java和Groovy声明范围可用。单击OK返回Editor。在Sandbox的声明部分,在mGreetings的定义下面,键入psfs然后按Ctrl + J | Cmd + J调用动态模板,然后按Enter键。给这个常数一个名称来完成这个声明并赋值,如 public static final String HELLO = “Hello Sandbox”;。
Note In Java, the naming convention for constants is all caps.Above the constructor, type the word CONSTRUCTORS. Now transform this word into a comment block that will catch other programmers’ attention. Select the entire word, CONSTRUCTORS, and then press Ctrl+Alt+J | Cmd+Alt+J to invoke Surround with Live
Template. Select cb from the Live Templates list and press Enter, as shown in Figure 3-19. You just applied the live template you created earlier.
<翻译>注意:在Java中,常量的命名约定是全部大写。在构造函数,输入CONSTRUCTORS这个单词。现在这个词转换成一个注释块好引起其他程序员的注意。选择整个词,CONSTRUCTOR,然后按Ctrl + Alt + J | Cmd + Alt + J弹出动态住模板。从动态模板列表中选择cb和按Enter键,如图3-19。你即可应用在前面创建的动态模板

技术分享图片

Figure 3-19. Apply the live template called cb (comment block)
图3-19 应用动态模板称为cb(注释块)
<翻译>****Moving Your Code
Android Studio understands how code blocks are delimited, so moving either lines or blocks of code is easy and intuitive. The difference between Move Statement and Move Line is that Move Statement respects both boundaries and scope, whereas Move Line respects neither. If you choose to move a statement of code with Move Statement, the statement will remain inside the boundaries of its enclosing block scope. If you move that same statement with Move Line, Android Studio treats the statement as a simple line of text, and will move it wherever you want it to go.
<翻译>Android Studio 可以感知代码块结束,所以按行或者代码块移动都是很容易和直观的。移动语句和移动行之间的差别是:移动语句代表着考虑界限和范围,而行不考虑。如果你选择有着Move Statement的代码语句来移动,该语句将保留它的块的边界范围。如果你移动相同的有着Move Line的语句,Android Studio将语句作为一个简单的行文本,并将它移动到任何你想要到的地方。
You can also move entire blocks of code. With Move Statement, all you need to do is place the cursor anywhere on the opening line (the one with the open curly brace) of the block you want to move and press Ctrl+Shift+Down | Cmd+Shift+Down or Ctrl+Shift+Up | Cmd+Shift+Up. The entire block will move en masse while respecting the boundaries of the other blocks and staying within the boundaries of its enclosing scope. Move Line doesn’t understand scope or boundaries, but you can still move multiple lines by selecting them first before applying the Move Line Up or Move Line Down operations, which are Alt+Shift+Up and Alt+Shift+Down, respectively, on both PC and Mac.
<翻译>你也可以移动整个代码块。 有了Move Statement,所有你需要做的是把光标放在你想移动的块的开始行(花括号的),按Ctrl + Shift + Down | Cmd + Shift +Down 或者Ctrl + Shift + Up| Cmd + Shift + Up,在考虑其他的边界块和保持封闭的边界范围内的情况下,整个块将集体移动。Move Line 不能识别范围或界限,但你仍然可以移动多行,通过 Alt + Shift + Up | Alt + Shift +Down(分别在PC和Mac中)实现Move Line Up or Move Line Down 操作。
To understand move operations in Android Studio, it’s best to just do them. Let’s start by creating a statement in our add() method. Directly after the line that reads return mGreetings.add(object);, press Enter to start a new line and type soutm. Then press Ctrl+J | Cmd+J to invoke Live Template, which produces System.out.println("Sandbox. add");. You may have noticed that your new line of code will not be reached because the return statement is above it, as shown in Figure 3-20. Let’s move this statement with Move Statement Up. While holding down Ctrl|Cmd and Shift, press the up-arrow key multiple times. Android Studio repositions the statement, but does not let you accidentally move this statement into a scope where it may not make any sense. Try this operation again with Move Line (Alt+Shift+Up) and observe its behavior again.
<翻译>要理解 Android Studio的移动操作,最好就是实践一下。首先让我们在add()方法中创建一个语句,随后直接返回mGreetings.add(object),按回车键并开始一个新行并键入soutm。然后按Ctrl + J | Cmd + J调用动态模板,会产生System.out.println(“Sandbox. add");。您可能已经注意到,你的新行代码将不会达到,因为返回语句在其上面,如图3-20所示。用Move Statement Up移动这个语句,同时按住Ctrl | Cmd和Shift,多次按向上箭头键。Android Studio 重新放置这个语句,但是不让你把这个语句移到一个可能没有任何意义的范围。再次尝试此操作 Move Line (Alt + Shift +Up),观察其行为。
技术分享图片

Figure 3-20. Move Statement and Move Line
<翻译>Move Statement 和 Move Line

Let’s try another example to demonstrate the power of Move Statement by moving your constructor to the bottom of our class. Make sure that there are no empty line breaks between the Sandbox() declaration and the comment block above it. Now, place your cursor anywhere on the declaration line of Sandbox() and invoke Move Statement Down by holding down the Ctrl|Cmd and Shift keys while pressing the down-arrow key repeatedly until your constructor is the last method in the class. Notice that the entire block, including the comment, leapfrogged down to the bottom of the class, avoiding the other methods along the way. The Move Code operations and their keyboard shortcuts are described in Table 3-5.
<翻译>让我们尝试一下另一个例子来演示移动Move Statement的强大:把构造函数移动到类的底部。确保Sandbox()声明和上面的注释块之间没有空换行。现在,把你的光标在声明的Sandbox(),并且按住Ctrl | Cmd和Shift键,同时按下箭头键来调用Move Statement Down,重复直到你的构造函数是类的最后一个方法。注意,整个块,包括注释,都移动到类的底部了,避免了其他方法。移动代码操作和键盘快捷键表如3 - 5所示。

技术分享图片


Styling Your Code
<翻译>样式代码
Code style conventions evolve. There are no hard-and-fast rules about the number of spaces you should place after your methods, or whether the opening curly brace should appear on the same line as the method signature or just below it. Organizations tend to define their own code styles, but code style also varies from one programmer to another; and you too probably have a code style with which you’re comfortable. Fortunately, Android Studio makes styling and organizing your code easy. Before you start styling your code,
let’s examine the Settings for Code Style. Choose File ? Settings ? Code Style to bring up the Settings dialog box, shown in Figure 3-21. Java and XML are the languages we’re most interested in for Android. Toggle open Code Style in the left pane, select Java, and examine each tab in the Settings window.
<翻译>代码风格规范在不断发展。没有固定的规则,你应该在你的方法之后放置空格的数量,还是左括号应该出现在同一行作为方法签名或略低于它。组织倾向于定义自己的代码风格,但每个程序员的代码风格也各不相同,你也可能有你习惯的代码风格。幸运的是,Android Studio很简单就能样式化和组织你的代码。在开始样式化代码之前,让我们检查一下代码风格的设置。选择File ? Settings ? Code Style弹出设置对话框,如图3 - 21所示。Java和XML是我们在Android中最感兴趣的语言。在左窗格中切换打开代码风格选项,选择Java,并检查在设置窗口的每个选项卡。

技术分享图片

Figure 3-21. Settings dialog box with Code Style ? Java selected and showing the Wrapping and Braces tab
<翻译>图3-21 代码风格?Java selected并显示包装和括号选项卡的设置对话框
Experiment with these settings by selecting/deselecting the check boxes in the middle pane of the various tabs and notice how the sample class in the right pane changes accordingly to suit your style. Click the Manage button along the top to define a new scheme. Now click Save As and give your scheme a name, such as android, and click OK. If you make further changes to a saved scheme, click the Apply button to apply them. When you format your code with Ctrl+Alt+L | Cmd+Alt+L, the settings you chose in the Code Style tabs will be applied. The code-organizing options are described in Table 3-6.
<翻译>通过在中间的面板的各种tab页的这些设置选择/取消选择复选框的实验,注意类在右窗格中发生相应变化,满足你的风格。点击Manage按钮在顶部定义一个新的架构。现在点击另存为,给您的架构起一个名字,比如android,并单击OK。如果你做出进一步更改保存方案,单击Apply按钮应用它们。当你用Ctrl + Alt + L | Cmd + Alt + L格式化你的代码,在代码中设置你选择的风格标签将被应用。代码组织的选项如表3 - 6所示。
技术分享图片


Auto-Indent Lines
<翻译>自动缩进行
Auto-Indent Lines is useful for keeping lines indented properly as you code. The rules that govern tabs and indents in Java are accessed via File ? Settings ? Code Style ? Java ? Tabs and Indents. Auto-Indent Lines is applied to the current line, or if you have multiple lines selected, to all the selected lines.
In Sandbox.java, select an entire method block of code and press Tab. The block should move one tab distance to the right. Now place the cursor on the first line of that block and press Ctrl+Alt+I on both PC and Mac. You will notice that Auto-Indent repositions that line to the appropriate indent position, although the rest of the method block remains unaffected.Now select all the code in the class by pressing Ctrl+A | Cmd+A and again press Ctrl+Alt+I.This time, proper indentation is applied to the entire file.
<翻译>自动缩进行有助于保持正常的行缩进代码。在Java中管理标签和缩进规则,通过File ? Settings ? Code Style ? Java ? Tabs and Indents。自动缩进线应用于当前行,或如果您有多个行选中,则是选中的所有行。
Sandbox.java,选择整个方法的代码块,按Tab键。块应该向右移动一个选项卡的距离。现在把光标放在第一行的块,按Ctrl + Alt +I(在PC和Mac中)。你会注意到自动缩进复位这条线到适当的缩进位置,尽管方法块的其余部分仍不受影响。现在选择的所有代码的类按Ctrl + I| Cmd +A,并且按Ctrl + Alt +I。这次,适当的缩进将会应用于整个文件。

Rearrange Code
<翻译>重新整理代码
Arrangement governs the order of the elements in your code. For example, most people prefer to keep class member declarations at the top of their classes, followed by constructors, followed by getters and setters, and so on. You can edit the Arrangement settings from the Arrangement tab accessed via File ? Settings ? Code Style ? Java ? Arrangement.In the previous section, you moved the constructor to the bottom of the class. This is not typically where it belongs. Choose Code ? Rearrange Code from the main menu. You will notice that your constructor has moved back to its expected position, below the declarations section. Rearrange Code performed this rearrangement operation according to the rules in the Arrangement settings.
<翻译>Arrangement管理代码中元素的顺序。例如,大多数人喜欢保持在类的顶部声明类成员,其次是构造函数,其次是getter和setter,等等。通过File ? Settings ? Code Style ? Java ? Arrangement,您可以编辑Arrangement的安排设置选项卡。在前面的部分中,您将构造函数的类。这不是通常他们在的地方。从主菜单 Code ? Rearrange。你会注意到构造函数已经搬回其预期的位置——声明部分的下面。Rearrange Code按照 Arrangement 的设置执行这种重排操作。

Reformat Code
<翻译>代码重新格式化

Reformat Code is the most powerful of the Code Style actions, as it gives you the option to apply all the code style options defined in the Code Style settings. As you’ve already seen, the Code Style settings can be accessed from the main menu via File ? Settings ? Code Style. In addition, Reformat Code allows you to reformat the currently selected file, or every file of the same type and directory. Furthermore, Reformat Code allows you to chain Rearrange Entries (which will apply Rearrange Code on Java files), and Optimize Imports onto the command, as shown in Figure 3-22. Try reformatting Sandbox.java by pressing Ctrl+Alt+L | cmd+Alt+L.
<翻译>重新格式化代码是在代码样式化中最强大的功能,因为它给了你选择应用的所有代码风格选项中定义的代码风格设置。正如您已经看到的,代码风格设置可以通过从主菜单中访问——File ? Settings ? Code Style。此外,重新格式化代码允许您重新格式化当前选择的文件,或相同类型的每个文件和目录。此外,重新格式化代码允许您链接重新排列条目(这将重新排列代码的Java文件),并优化导入到命令,如图3-22。按Ctrl + Alt + L | cmd + Alt + L,尝试重新格式化Sandbox.java。
技术分享图片

Figure 3-22. Reformat Code dialog box with Rearrange Entries selected
<翻译>图3-2 包含重新整理条目选择的重新格式化代码对话框

Surrounding With
<翻译>环绕
Surround With (Ctrl+Alt+T | Cmd+Alt+T) is a superset of the functionality found in Surround with Live Template (Ctrl+Alt+J | Cmd+Alt+J). However, Surround With also includes options to surround a selected statement or statements with a Java block such as if/else, for, try/catch, and so on. Although the simple code in your Sandbox class does not threaten to throw any checked exceptions, surrounding statements that threaten to throw exceptions with try/catch blocks is among the best application of Surround With; and this is probably why the keyboard shortcut Ctrl+Alt+T | Cmd+Alt+T includes a T. The Surround With operations are described in Table 3-7.
<翻译>环绕(Ctrl + Alt + T | Cmd + Alt + T)是一个在周围发现功能的超集,环绕动态模板(Ctrl + Alt + J | Cmd + Alt + J)。然而,环绕还包括选项来选择与Java语句或语句块周围如if / else,try / catch等等。虽然在你的Sandbox 类中,简单的代码不可能产生任何受控异常,周围的语句可能抛出异常的try / catch块的周围是最好的应用,这可能是为什么键盘快捷键Ctrl + Alt + T | Cmd + Alt + T包括一个T。环绕的操作如表3 - 7所示。
技术分享图片

In the add() method of Sandbox.java, you want to ensure that there are no duplicates. Let’s surround the return mGreetings.add(object); with an if/else block, as shown in Figure 3-23. Select that entire line and press Ctrl+Alt+T | Cmd+Alt+T to activate Surround With. Now select if/else from the menu. In the parentheses of the if statement, type !mGreetings. contains(object) and in the else block type return false;.
<翻译>在Sandbox.java的add()方法中,您希望确保没有重复的。让我们用一个if / else块围绕 return mGreetings.add(Object); 如图3-23。选择整行,按Ctrl + Alt + T | Cmd + Alt + T激活周围。现在从菜单中选择if / else。在if的括号里键入!mGreetings. contains(object) ,在else块返回false;。

技术分享图片

Figure 3-23. Wrapping and unwrapping blocks of code with Surround With
<翻译>图3-23 用Surround With包装和打开代码块

Say your business rules have changed and you don’t care about duplicate entries in mGreetings anymore. Use Unwrap/Remove to remove the if/else block you just created. Place your cursor anywhere on the return mGreetings.add(object); statement, press Ctrl+Shift+Delete | Cmd+Shift+Delete, and select unwrap if. The method should now look as it did before you modified it.
Another great application of Surround With is iterating over collections. In the previous section, you auto-generated a toString() method. Now change this method so that you iterate over the mGreetings collection. Remove the return statement from the toString() method so that the body of the toString() method is empty. Now type mGreetings and then press Ctrl+Alt+T | Cmd+Alt+T. Select Iterate Iterable from the list, or press the I key. Press Enter again to accept greeting as the name of the individual element. The resulting code is a for-each loop. Notice that Android Studio understood that mGreetings contains Strings, and that it also generated a local variable called greeting with the singular form of mGreetings less the m. Modify the add() method further, per Figure 3-24.
<翻译>假如你的业务规则已经改变,你不再关心mGreetings重复的条目了。使用Unwrap/Remove删除刚才创建的if / else块。把你的光标在return mGreetings.add(object);语句的任何位置,按Ctrl + Shift +Delete| Cmd + Shift +Delete,并选择打开。该方法现在看起来应该像之前你修改它的那样。
环绕的另一个伟大的应用是遍历集合。在前面的小节中自动生成toString()方法。现在改变这种方法遍历mGreetings集合。删除toString()方法的返回语句,确保toString()方法的主体是空的。现在键入mGreetings,然后按Ctrl + Alt + T | Cmd + Alt + T。从列表中选择迭代Iterable,或者按I键。再次按下Enter接受greeting 作为单个元素的名称。生成的代码是一个for - each循环。注意到Android Studio明白mGreetings包含字符串,而且它也产生一个局部变量叫做greeting ——mGreetings缺少 m的单数形式。进一步修改add()方法,如图3-24。

Summary
<翻译>小结
This chapter covered the most important code-generation features of Android Studio. We encourage you to return to File ? Settings ? Code Style ? Java and File ? Settings ? Code Style ? and spend a few minutes exploring the various settings there. Android Studio provides a lot of keyboard shortcuts for coding, but you don’t have to remember them all. If you get overwhelmed, you can use this book as a reference, or navigate to the Code menu and explore its menu items and submenus as a reference.
<翻译>本章涵盖了Android Studio最重要的代码生成功能。我们鼓励您返回File ? Settings ? Code Style ? Java and File ? Settings ? Code Style ?,并花几分钟探索各种设置。Android Studio为编码提供了很多快捷键,但你不必记得。如果你会不知所措,你可以使用本书作为参考,或者导航到Code菜单和探索其菜单项和子菜单作为参考。

勘误感谢:Sohnyi ,zhin
技术分享图片

第三章:使用 Android Studio 编程[Learn Android Studio 汉化教程]

标签:固定   its   使用   reference   cat   覆盖   c中   uil   direct   

原文地址:http://www.cnblogs.com/zjgwh/p/8051675.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!