Difference between revisions of "The Basics of the Android Studio Code Editor"
m (Text replacement - "<table border="0" cellspacing="0"> " to "<table border="0" cellspacing="0" width="100%">") |
|||
Line 1: | Line 1: | ||
+ | The Basics of the Android Studio Code Editor | ||
+ | |||
+ | Developing applications for Android involves a considerable amount of programming work which, by definition, involves typing, reviewing and modifying lines of code. It should come as no surprise that the majority of a developer’s time spent using Android Studio will typically involve editing code within the editor window. | ||
+ | |||
+ | The modern code editor needs to go far beyond the original basics of typing, deleting, cutting and pasting. Today the usefulness of a code editor is generally gauged by factors such as the amount by which it reduces the typing required by the programmer, ease of navigation through large source code files and the editor’s ability to detect and highlight programming errors in real-time as the code is being written. As will become evident in this chapter, these are just a few of the areas in which the Android Studio editor excels. | ||
+ | |||
+ | While not an exhaustive overview of the features of the Android Studio editor, this chapter aims to provide a guide to the key features of the tool. Experienced programmers will find that some of these features are common to most code editors available today, while a number are unique to this particular editing environment. | ||
+ | |||
+ | == The Android Studio Editor == | ||
+ | |||
+ | The Android Studio editor appears in the center of the main window when a Java, Kotlin, XML or other text based file is selected for editing. Figure 8-1, for example, shows a typical editor session with a Java source code file loaded: | ||
+ | |||
+ | |||
+ | [[Image:.png]] | ||
+ | |||
+ | |||
+ | The elements that comprise the editor window can be summarized as follows: | ||
+ | |||
+ | A – Document Tabs – Android Studio is capable of holding multiple files open for editing at any one time. As each file is opened, it is assigned a document tab displaying the file name in the tab bar located along the top edge of the editor window. A small dropdown menu will appear in the far right-hand corner of the tab bar when there is insufficient room to display all of the tabs. Clicking on this menu will drop down a list of additional open files. A wavy red line underneath a file name in a tab indicates that the code in the file contains one or more errors that need to be addressed before the project can be compiled and run. | ||
+ | |||
+ | Switching between files is simply a matter of clicking on the corresponding tab or using the Alt-Left and Alt-Right keyboard shortcuts. Navigation between files may also be performed using the Switcher mechanism (accessible via the Ctrl-Tab keyboard shortcut). | ||
+ | |||
+ | To detach an editor panel from the Android Studio main window so that it appears in a separate window, click on the tab and drag it to an area on the desktop outside of the main window. To return the editor to the main window, click on the file tab in the separated editor window and drag and drop it onto the original editor tab bar in the main window. | ||
+ | |||
+ | * '''B – The Editor Gutter Area''' - The gutter area is used by the editor to display informational icons and controls. Some typical items, among others, which appear in this gutter area are debugging breakpoint markers, controls to fold and unfold blocks of code, bookmarks, change markers and line numbers. Line numbers are switched on by default but may be disabled by right-clicking in the gutter and selecting the Show Line Numbers menu option. | ||
+ | |||
+ | * '''C – The Status Bar''' – Though the status bar is actually part of the main window, as opposed to the editor, it does contain some information about the currently active editing session. This information includes the current position of the cursor in terms of lines and characters and the encoding format of the file (UTF-8, ASCII etc.). Clicking on these values in the status bar allows the corresponding setting to be changed. Clicking on the line number, for example, displays the Go to Line dialog. | ||
+ | |||
+ | * '''D – The Editor Area''' – This is the main area where the code is displayed, entered and edited by the user. Later sections of this chapter will cover the key features of the editing area in detail. | ||
+ | |||
+ | * '''E – The Validation and Marker Sidebar''' – Android Studio incorporates a feature referred to as “on-the-fly code analysis”. What this essentially means is that as you are typing code, the editor is analyzing the code to check for warnings and syntax errors. The indicator at the top of the validation sidebar will change from a green check mark (no warnings or errors detected) to a yellow square (warnings detected) or red alert icon (errors have been detected). Clicking on this indicator will display a popup containing a summary of the issues found with the code in the editor as illustrated in Figure 8-2: | ||
+ | |||
+ | |||
+ | [[Image:.png]] | ||
+ | |||
+ | |||
+ | The sidebar also displays markers at the locations where issues have been detected using the same color coding. Hovering the mouse pointer over a marker when the line of code is visible in the editor area will display a popup containing a description of the issue (Figure 8-3): | ||
+ | |||
+ | |||
+ | [[Image:.png]] | ||
+ | |||
+ | |||
+ | Hovering the mouse pointer over a marker for a line of code which is currently scrolled out of the viewing area of the editor will display a “lens” overlay containing the block of code where the problem is located (Figure 8-4) allowing it to be viewed without the necessity to scroll to that location in the editor: | ||
+ | |||
+ | |||
+ | [[Image:.png]] | ||
+ | |||
+ | |||
+ | It is also worth noting that the lens overlay is not limited to warnings and errors in the sidebar. Hovering over any part of the sidebar will result in a lens appearing containing the code present at that location within the source file. | ||
+ | |||
+ | Having provided an overview of the elements that comprise the Android Studio editor, the remainder of this chapter will explore the key features of the editing environment in more detail. | ||
+ | |||
+ | == Splitting the Editor Window == | ||
+ | |||
+ | By default, the editor will display a single panel showing the content of the currently selected file. A particularly useful feature when working simultaneously with multiple source code files is the ability to split the editor into multiple panes. To split the editor, right-click on a file tab within the editor window and select either the Split Vertically or Split Horizontally menu option. Figure 8-5, for example, shows the splitter in action with the editor split into three panels: | ||
+ | |||
+ | |||
+ | [[Image:.png]] | ||
+ | |||
+ | |||
+ | The orientation of a split panel may be changed at any time by right-clicking on the corresponding tab and selecting the Change Splitter Orientation menu option. Repeat these steps to unsplit a single panel, this time selecting the Unsplit option from the menu. All of the split panels may be removed by right-clicking on any tab and selecting the Unsplit All menu option. | ||
+ | |||
+ | Window splitting may be used to display different files, or to provide multiple windows onto the same file, allowing different areas of the same file to be viewed and edited concurrently. | ||
+ | |||
+ | == Code Completion == | ||
+ | |||
+ | The Android Studio editor has a considerable amount of built-in knowledge of programming syntax and the classes and methods that make up the Android SDK, as well as knowledge of your own code base. As code is typed, the editor scans what is being typed and, where appropriate, makes suggestions with regard to what might be needed to complete a statement or reference. When a completion suggestion is detected by the editor, a panel will appear containing a list of suggestions. In Figure 8-6, for example, the editor is suggesting possibilities for the beginning of a String declaration: | ||
+ | |||
+ | |||
+ | [[Image:.png]] | ||
+ | |||
+ | |||
+ | If none of the auto completion suggestions are correct, simply keep typing and the editor will continue to refine the suggestions where appropriate. To accept the top most suggestion, simply press the Enter or Tab key on the keyboard. To select a different suggestion, use the arrow keys to move up and down the list, once again using the Enter or Tab key to select the highlighted item. | ||
+ | |||
+ | Completion suggestions can be manually invoked using the Ctrl-Space keyboard sequence. This can be useful when changing a word or declaration in the editor. When the cursor is positioned over a word in the editor, that word will automatically highlight. Pressing Ctrl-Space will display a list of alternate suggestions. To replace the current word with the currently highlighted item in the suggestion list, simply press the Tab key. | ||
+ | |||
+ | In addition to the real-time auto completion feature, the Android Studio editor also offers a system referred to as Smart Completion. Smart completion is invoked using the Shift-Ctrl-Space keyboard sequence and, when selected, will provide more detailed suggestions based on the current context of the code. Pressing the Shift-Ctrl-Space shortcut sequence a second time will provide more suggestions from a wider range of possibilities. | ||
+ | |||
+ | Code completion can be a matter of personal preference for many programmers. In recognition of this fact, Android Studio provides a high level of control over the auto completion settings. These can be viewed and modified by selecting the File -> Settings… menu option (or Android Studio -> Preferences… on macOS) and choosing Editor -> General -> Code Completion from the settings panel as shown in Figure 8-7: | ||
+ | |||
+ | |||
+ | [[Image:.png]] | ||
+ | |||
+ | |||
+ | == Statement Completion == | ||
+ | |||
+ | Another form of auto completion provided by the Android Studio editor is statement completion. This can be used to automatically fill out the parentheses and braces for items such as methods and loop statements. Statement completion is invoked using the Shift-Ctrl-Enter (Shift-Cmd-Enter on macOS) keyboard sequence. Consider for example the following code: | ||
+ | |||
+ | <pre> | ||
+ | myMethod() | ||
+ | </pre> | ||
+ | |||
+ | Having typed this code into the editor, triggering statement completion will cause the editor to automatically add the braces to the method: | ||
+ | |||
+ | <pre> | ||
+ | myMethod() { | ||
+ | |||
+ | } | ||
+ | </pre> | ||
+ | |||
+ | == Parameter Information == | ||
+ | |||
+ | It is also possible to ask the editor to provide information about the argument parameters accepted by a method. With the cursor positioned between the brackets of a method call, the Ctrl-P (Cmd-P on macOS) keyboard sequence will display the parameters known to be accepted by that method, with the most likely suggestion highlighted in bold: | ||
+ | |||
+ | |||
+ | [[Image:.png]] | ||
+ | |||
+ | |||
+ | == Parameter Name Hints == | ||
+ | |||
+ | The code editor may be configured to display parameter name hints within method calls. Figure 8-9, for example, highlights the parameter name hints within the calls to the make() and setAction() methods of the Snackbar class: | ||
+ | |||
+ | |||
+ | [[Image:.png]] | ||
+ | |||
+ | |||
+ | The settings for this mode may be configured by selecting the File -> Settings (Android Studio -> Preferences on macOS) menu option followed by Editor -> Appearance in the left-hand panel. On the Appearance screen, enable or disable the Show parameter name hints option. To adjust the hint settings, click on the Configure... button, select the programming language and make any necessary adjustments. | ||
+ | |||
+ | == Code Generation == | ||
+ | |||
+ | In addition to completing code as it is typed the editor can, under certain conditions, also generate code for you. The list of available code generation options shown in Figure 8-10 can be accessed using the Alt-Insert (Cmd-N on macOS) keyboard shortcut when the cursor is at the location in the file where the code is to be generated. | ||
+ | |||
+ | |||
+ | [[Image:.png]] | ||
+ | |||
+ | |||
+ | For the purposes of an example, consider a situation where we want to be notified when an Activity in our project is about to be destroyed by the operating system. As will be outlined in a later chapter of this book, this can be achieved by overriding the onStop() lifecycle method of the Activity superclass. To have Android Studio generate a stub method for this, simply select the Override Methods… option from the code generation list and select the onStop() method from the resulting list of available methods: | ||
+ | |||
+ | |||
+ | [[Image:.png]] | ||
+ | |||
+ | |||
+ | Having selected the method to override, clicking on OK will generate the stub method at the current cursor location in the Java source file as follows: | ||
+ | |||
+ | <pre> | ||
+ | @Override | ||
+ | protected void onStop() { | ||
+ | super.onStop(); | ||
+ | } | ||
+ | </pre> | ||
+ | |||
+ | == Code Folding == | ||
+ | |||
+ | Once a source code file reaches a certain size, even the most carefully formatted and well organized code can become overwhelming and difficult to navigate. Android Studio takes the view that it is not always necessary to have the content of every code block visible at all times. Code navigation can be made easier through the use of the code folding feature of the Android Studio editor. Code folding is controlled using markers appearing in the editor gutter at the beginning and end of each block of code in a source file. Figure 8-12, for example, highlights the start and end markers for a method declaration which is not currently folded: | ||
+ | |||
+ | |||
+ | [[Image:.png]] | ||
+ | |||
+ | |||
+ | Clicking on either of these markers will fold the statement such that only the signature line is visible as shown in Figure 8-13: | ||
+ | |||
+ | |||
+ | [[Image:.png]] | ||
+ | |||
+ | |||
+ | To unfold a collapsed section of code, simply click on the ‘+’ marker in the editor gutter. To see the hidden code without unfolding it, hover the mouse pointer over the “{…}” indicator as shown in Figure 8-14. The editor will then display the lens overlay containing the folded code block: | ||
+ | |||
+ | |||
+ | [[Image:.png]] | ||
+ | |||
+ | |||
+ | All of the code blocks in a file may be folded or unfolded using the Ctrl-Shift-Plus and Ctrl-Shift-Minus keyboard sequences. | ||
+ | |||
+ | By default, the Android Studio editor will automatically fold some code when a source file is opened. To configure the conditions under which this happens, select File -> Settings… (Android Studio -> Preferences… on macOS) and choose the Editor -> General -> Code Folding entry in the resulting settings panel (Figure 8-15): | ||
+ | |||
+ | |||
+ | [[Image:.png]] | ||
+ | |||
+ | |||
+ | == Quick Documentation Lookup == | ||
+ | |||
+ | Context sensitive Java and Android documentation can be accessed by placing the cursor over the declaration for which documentation is required and pressing the Ctrl-Q keyboard shortcut (Ctrl-J on macOS). This will display a popup containing the relevant reference documentation for the item. Figure 8-16, for example, shows the documentation for the Android Snackbar class. | ||
+ | |||
+ | |||
+ | [[Image:.png]] | ||
+ | |||
+ | |||
+ | Once displayed, the documentation popup can be moved around the screen as needed. Clicking on the push pin icon located in the right-hand corner of the popup title bar will ensure that the popup remains visible once focus moves back to the editor, leaving the documentation visible as a reference while typing code. | ||
+ | |||
+ | == Code Reformatting == | ||
+ | |||
+ | In general, the Android Studio editor will automatically format code in terms of indenting, spacing and nesting of statements and code blocks as they are added. In situations where lines of code need to be reformatted (a common occurrence, for example, when cutting and pasting sample code from a web site), the editor provides a source code reformatting feature which, when selected, will automatically reformat code to match the prevailing code style. | ||
+ | |||
+ | To reformat source code, press the Ctrl-Alt-L (Cmd-Alt-L on macOS) keyboard shortcut sequence. To display the Reformat Code dialog (Figure 8-17) use the Ctrl-Alt-Shift-L (Cmd-Alt-Shift-L on macOS). This dialog provides the option to reformat only the currently selected code, the entire source file currently active in the editor or only code that has changed as the result of a source code control update. | ||
+ | |||
+ | |||
+ | [[Image:.png]] | ||
+ | |||
+ | |||
+ | The full range of code style preferences can be changed from within the project settings dialog. Select the File -> Settings menu option (Android Studio -> Preferences… on macOS) and choose Code Style in the left-hand panel to access a list of supported programming and markup languages. Selecting a language will provide access to a vast array of formatting style options, all of which may be modified from the Android Studio default to match your preferred code style. To configure the settings for the Rearrange code option in the above dialog, for example, unfold the Code Style section, select Java and, from the Java settings, select the Arrangement tab. | ||
+ | |||
+ | == Finding Sample Code == | ||
+ | |||
+ | The Android Studio editor provides a way to access sample code relating to the currently highlighted entry within the code listing. This feature can be useful for learning how a particular Android class or method is used. To find sample code, highlight a method or class name in the editor, right-click on it and select the Find Sample Code menu option. The Find Sample Code panel (Figure 8-18) will appear beneath the editor with a list of matching samples. Selecting a sample from the list will load the corresponding code into the right-hand panel: | ||
+ | |||
+ | |||
+ | [[Image:.png]] | ||
+ | |||
+ | |||
+ | == Summary == | ||
+ | |||
+ | The Android Studio editor goes to great length to reduce the amount of typing needed to write code and to make that code easier to read and navigate. In this chapter we have covered a number of the key editor features including code completion, code generation, editor window splitting, code folding, reformatting and documentation lookup. | ||
+ | |||
+ | |||
+ | |||
+ | |||
<table border="0" cellspacing="0" width="100%"><tr> | <table border="0" cellspacing="0" width="100%"><tr> | ||
<td width="20%">[[Testing Android Studio Apps on a Physical Android Device|Previous]]<td align="center">[[Android Studio Development Essentials|Table of Contents]]<td width="20%" align="right">[[An Overview of the Android Architecture (Android Studio)|Next]]</td> | <td width="20%">[[Testing Android Studio Apps on a Physical Android Device|Previous]]<td align="center">[[Android Studio Development Essentials|Table of Contents]]<td width="20%" align="right">[[An Overview of the Android Architecture (Android Studio)|Next]]</td> |
Revision as of 21:34, 8 January 2019
The Basics of the Android Studio Code Editor
Developing applications for Android involves a considerable amount of programming work which, by definition, involves typing, reviewing and modifying lines of code. It should come as no surprise that the majority of a developer’s time spent using Android Studio will typically involve editing code within the editor window.
The modern code editor needs to go far beyond the original basics of typing, deleting, cutting and pasting. Today the usefulness of a code editor is generally gauged by factors such as the amount by which it reduces the typing required by the programmer, ease of navigation through large source code files and the editor’s ability to detect and highlight programming errors in real-time as the code is being written. As will become evident in this chapter, these are just a few of the areas in which the Android Studio editor excels.
While not an exhaustive overview of the features of the Android Studio editor, this chapter aims to provide a guide to the key features of the tool. Experienced programmers will find that some of these features are common to most code editors available today, while a number are unique to this particular editing environment.
The Android Studio Editor
The Android Studio editor appears in the center of the main window when a Java, Kotlin, XML or other text based file is selected for editing. Figure 8-1, for example, shows a typical editor session with a Java source code file loaded:
The elements that comprise the editor window can be summarized as follows:
A – Document Tabs – Android Studio is capable of holding multiple files open for editing at any one time. As each file is opened, it is assigned a document tab displaying the file name in the tab bar located along the top edge of the editor window. A small dropdown menu will appear in the far right-hand corner of the tab bar when there is insufficient room to display all of the tabs. Clicking on this menu will drop down a list of additional open files. A wavy red line underneath a file name in a tab indicates that the code in the file contains one or more errors that need to be addressed before the project can be compiled and run.
Switching between files is simply a matter of clicking on the corresponding tab or using the Alt-Left and Alt-Right keyboard shortcuts. Navigation between files may also be performed using the Switcher mechanism (accessible via the Ctrl-Tab keyboard shortcut).
To detach an editor panel from the Android Studio main window so that it appears in a separate window, click on the tab and drag it to an area on the desktop outside of the main window. To return the editor to the main window, click on the file tab in the separated editor window and drag and drop it onto the original editor tab bar in the main window.
- B – The Editor Gutter Area - The gutter area is used by the editor to display informational icons and controls. Some typical items, among others, which appear in this gutter area are debugging breakpoint markers, controls to fold and unfold blocks of code, bookmarks, change markers and line numbers. Line numbers are switched on by default but may be disabled by right-clicking in the gutter and selecting the Show Line Numbers menu option.
- C – The Status Bar – Though the status bar is actually part of the main window, as opposed to the editor, it does contain some information about the currently active editing session. This information includes the current position of the cursor in terms of lines and characters and the encoding format of the file (UTF-8, ASCII etc.). Clicking on these values in the status bar allows the corresponding setting to be changed. Clicking on the line number, for example, displays the Go to Line dialog.
- D – The Editor Area – This is the main area where the code is displayed, entered and edited by the user. Later sections of this chapter will cover the key features of the editing area in detail.
- E – The Validation and Marker Sidebar – Android Studio incorporates a feature referred to as “on-the-fly code analysis”. What this essentially means is that as you are typing code, the editor is analyzing the code to check for warnings and syntax errors. The indicator at the top of the validation sidebar will change from a green check mark (no warnings or errors detected) to a yellow square (warnings detected) or red alert icon (errors have been detected). Clicking on this indicator will display a popup containing a summary of the issues found with the code in the editor as illustrated in Figure 8-2:
The sidebar also displays markers at the locations where issues have been detected using the same color coding. Hovering the mouse pointer over a marker when the line of code is visible in the editor area will display a popup containing a description of the issue (Figure 8-3):
Hovering the mouse pointer over a marker for a line of code which is currently scrolled out of the viewing area of the editor will display a “lens” overlay containing the block of code where the problem is located (Figure 8-4) allowing it to be viewed without the necessity to scroll to that location in the editor:
It is also worth noting that the lens overlay is not limited to warnings and errors in the sidebar. Hovering over any part of the sidebar will result in a lens appearing containing the code present at that location within the source file.
Having provided an overview of the elements that comprise the Android Studio editor, the remainder of this chapter will explore the key features of the editing environment in more detail.
Splitting the Editor Window
By default, the editor will display a single panel showing the content of the currently selected file. A particularly useful feature when working simultaneously with multiple source code files is the ability to split the editor into multiple panes. To split the editor, right-click on a file tab within the editor window and select either the Split Vertically or Split Horizontally menu option. Figure 8-5, for example, shows the splitter in action with the editor split into three panels:
The orientation of a split panel may be changed at any time by right-clicking on the corresponding tab and selecting the Change Splitter Orientation menu option. Repeat these steps to unsplit a single panel, this time selecting the Unsplit option from the menu. All of the split panels may be removed by right-clicking on any tab and selecting the Unsplit All menu option.
Window splitting may be used to display different files, or to provide multiple windows onto the same file, allowing different areas of the same file to be viewed and edited concurrently.
Code Completion
The Android Studio editor has a considerable amount of built-in knowledge of programming syntax and the classes and methods that make up the Android SDK, as well as knowledge of your own code base. As code is typed, the editor scans what is being typed and, where appropriate, makes suggestions with regard to what might be needed to complete a statement or reference. When a completion suggestion is detected by the editor, a panel will appear containing a list of suggestions. In Figure 8-6, for example, the editor is suggesting possibilities for the beginning of a String declaration:
If none of the auto completion suggestions are correct, simply keep typing and the editor will continue to refine the suggestions where appropriate. To accept the top most suggestion, simply press the Enter or Tab key on the keyboard. To select a different suggestion, use the arrow keys to move up and down the list, once again using the Enter or Tab key to select the highlighted item.
Completion suggestions can be manually invoked using the Ctrl-Space keyboard sequence. This can be useful when changing a word or declaration in the editor. When the cursor is positioned over a word in the editor, that word will automatically highlight. Pressing Ctrl-Space will display a list of alternate suggestions. To replace the current word with the currently highlighted item in the suggestion list, simply press the Tab key.
In addition to the real-time auto completion feature, the Android Studio editor also offers a system referred to as Smart Completion. Smart completion is invoked using the Shift-Ctrl-Space keyboard sequence and, when selected, will provide more detailed suggestions based on the current context of the code. Pressing the Shift-Ctrl-Space shortcut sequence a second time will provide more suggestions from a wider range of possibilities.
Code completion can be a matter of personal preference for many programmers. In recognition of this fact, Android Studio provides a high level of control over the auto completion settings. These can be viewed and modified by selecting the File -> Settings… menu option (or Android Studio -> Preferences… on macOS) and choosing Editor -> General -> Code Completion from the settings panel as shown in Figure 8-7:
Statement Completion
Another form of auto completion provided by the Android Studio editor is statement completion. This can be used to automatically fill out the parentheses and braces for items such as methods and loop statements. Statement completion is invoked using the Shift-Ctrl-Enter (Shift-Cmd-Enter on macOS) keyboard sequence. Consider for example the following code:
myMethod()
Having typed this code into the editor, triggering statement completion will cause the editor to automatically add the braces to the method:
myMethod() { }
Parameter Information
It is also possible to ask the editor to provide information about the argument parameters accepted by a method. With the cursor positioned between the brackets of a method call, the Ctrl-P (Cmd-P on macOS) keyboard sequence will display the parameters known to be accepted by that method, with the most likely suggestion highlighted in bold:
Parameter Name Hints
The code editor may be configured to display parameter name hints within method calls. Figure 8-9, for example, highlights the parameter name hints within the calls to the make() and setAction() methods of the Snackbar class:
The settings for this mode may be configured by selecting the File -> Settings (Android Studio -> Preferences on macOS) menu option followed by Editor -> Appearance in the left-hand panel. On the Appearance screen, enable or disable the Show parameter name hints option. To adjust the hint settings, click on the Configure... button, select the programming language and make any necessary adjustments.
Code Generation
In addition to completing code as it is typed the editor can, under certain conditions, also generate code for you. The list of available code generation options shown in Figure 8-10 can be accessed using the Alt-Insert (Cmd-N on macOS) keyboard shortcut when the cursor is at the location in the file where the code is to be generated.
For the purposes of an example, consider a situation where we want to be notified when an Activity in our project is about to be destroyed by the operating system. As will be outlined in a later chapter of this book, this can be achieved by overriding the onStop() lifecycle method of the Activity superclass. To have Android Studio generate a stub method for this, simply select the Override Methods… option from the code generation list and select the onStop() method from the resulting list of available methods:
Having selected the method to override, clicking on OK will generate the stub method at the current cursor location in the Java source file as follows:
@Override protected void onStop() { super.onStop(); }
Code Folding
Once a source code file reaches a certain size, even the most carefully formatted and well organized code can become overwhelming and difficult to navigate. Android Studio takes the view that it is not always necessary to have the content of every code block visible at all times. Code navigation can be made easier through the use of the code folding feature of the Android Studio editor. Code folding is controlled using markers appearing in the editor gutter at the beginning and end of each block of code in a source file. Figure 8-12, for example, highlights the start and end markers for a method declaration which is not currently folded:
Clicking on either of these markers will fold the statement such that only the signature line is visible as shown in Figure 8-13:
To unfold a collapsed section of code, simply click on the ‘+’ marker in the editor gutter. To see the hidden code without unfolding it, hover the mouse pointer over the “{…}” indicator as shown in Figure 8-14. The editor will then display the lens overlay containing the folded code block:
All of the code blocks in a file may be folded or unfolded using the Ctrl-Shift-Plus and Ctrl-Shift-Minus keyboard sequences.
By default, the Android Studio editor will automatically fold some code when a source file is opened. To configure the conditions under which this happens, select File -> Settings… (Android Studio -> Preferences… on macOS) and choose the Editor -> General -> Code Folding entry in the resulting settings panel (Figure 8-15):
Quick Documentation Lookup
Context sensitive Java and Android documentation can be accessed by placing the cursor over the declaration for which documentation is required and pressing the Ctrl-Q keyboard shortcut (Ctrl-J on macOS). This will display a popup containing the relevant reference documentation for the item. Figure 8-16, for example, shows the documentation for the Android Snackbar class.
Once displayed, the documentation popup can be moved around the screen as needed. Clicking on the push pin icon located in the right-hand corner of the popup title bar will ensure that the popup remains visible once focus moves back to the editor, leaving the documentation visible as a reference while typing code.
Code Reformatting
In general, the Android Studio editor will automatically format code in terms of indenting, spacing and nesting of statements and code blocks as they are added. In situations where lines of code need to be reformatted (a common occurrence, for example, when cutting and pasting sample code from a web site), the editor provides a source code reformatting feature which, when selected, will automatically reformat code to match the prevailing code style.
To reformat source code, press the Ctrl-Alt-L (Cmd-Alt-L on macOS) keyboard shortcut sequence. To display the Reformat Code dialog (Figure 8-17) use the Ctrl-Alt-Shift-L (Cmd-Alt-Shift-L on macOS). This dialog provides the option to reformat only the currently selected code, the entire source file currently active in the editor or only code that has changed as the result of a source code control update.
The full range of code style preferences can be changed from within the project settings dialog. Select the File -> Settings menu option (Android Studio -> Preferences… on macOS) and choose Code Style in the left-hand panel to access a list of supported programming and markup languages. Selecting a language will provide access to a vast array of formatting style options, all of which may be modified from the Android Studio default to match your preferred code style. To configure the settings for the Rearrange code option in the above dialog, for example, unfold the Code Style section, select Java and, from the Java settings, select the Arrangement tab.
Finding Sample Code
The Android Studio editor provides a way to access sample code relating to the currently highlighted entry within the code listing. This feature can be useful for learning how a particular Android class or method is used. To find sample code, highlight a method or class name in the editor, right-click on it and select the Find Sample Code menu option. The Find Sample Code panel (Figure 8-18) will appear beneath the editor with a list of matching samples. Selecting a sample from the list will load the corresponding code into the right-hand panel:
Summary
The Android Studio editor goes to great length to reduce the amount of typing needed to write code and to make that code easier to read and navigate. In this chapter we have covered a number of the key editor features including code completion, code generation, editor window splitting, code folding, reformatting and documentation lookup.
Previous | Table of Contents | Next |
Testing Android Studio Apps on a Physical Android Device | An Overview of the Android Architecture |
Developing applications for Android involves a considerable amount of programming work which, by definition, involves typing, reviewing and modifying lines of code. It should come as no surprise that the majority of a developer’s time spent using Android Studio will typically involve editing code within the editor window.
The modern code editor needs to go far beyond the original basics of typing, deleting, cutting and pasting. Today the usefulness of a code editor is generally gauged by factors such as the amount by which it reduces the typing required by the programmer, ease of navigation through large source code files and the editor’s ability to detect and highlight programming errors in real-time as the code is being written. As will become evident in this chapter, these are just a few of the areas in which the Android Studio editor excels.
Whilst not an exhaustive overview of the features of the Android Studio editor, this chapter aims to provide a guide to the key features of the tool. Experienced programmers will find that some of these features are common to most code editors available today, whilst a number are unique to this particular editing environment.
The Android Studio Editor
The Android Studio editor appears in the center of the main window when a Java, XML or other text based file is selected for editing. Figure 7-1, for example, shows a typical editor session with a Java source code file loaded:
Figure 7-1
The elements that comprise the editor window can be summarized as follows:
A – Document Tabs – Android Studio is capable of holding multiple files open for editing at any one time. As each file is opened, it is assigned a document tab displaying the file name in the tab bar located along the top edge of the editor window. A small dropdown menu will appear in the far right hand corner of the tab bar when there is insufficient room to display all of the tabs. Clicking on this menu will drop down a list of additional open files. A wavy red line underneath a file name in a tab indicates that the code in the file contains one or more errors that need to be addressed before the project can be compiled and run.
Switching between files is simply a matter of clicking on the corresponding tab or using the Alt-Left and Alt-Right keyboard shortcuts. Navigation between files may also be performed using the Switcher mechanism (accessible via the Ctrl-Tab keyboard shortcut).
To detach an editor panel from the Android Studio main window so that it appears in a separate window, click on the tab and drag it to an area on the desktop outside of the main window. To return the editor to the main window, click on the file tab in the separated editor window and drag and drop it onto the original editor tab bar in the main window.
B – The Editor Gutter Area - The gutter area is used by the editor to display informational icons and controls. Some typical items, among others, which appear in this gutter area are debugging breakpoint markers, controls to fold and unfold blocks of code, bookmarks, change markers and line numbers. Line numbers are switched off by default but may be enabled by right-clicking in the gutter and selecting the Show Line Numbers menu option.
C – The Status Bar – Though the status bar is actually part of the main window, as opposed to the editor, it does contain some information about the currently active editing session. This information includes the current position of the cursor in terms of lines and characters and the encoding format of the file (UTF-8, ASCII etc.). Clicking on these values in the status bar allows the corresponding setting to be changed. Clicking on the line number, for example, displays the Go to Line dialog.
D – The Editor Area – This is the main area where the code is displayed, entered and edited by the user. Later sections of this chapter will cover the key features of the editing area in detail.
E – The Validation and Marker Sidebar – Android Studio incorporates a feature referred to as “on-the-fly code analysis”. What this essentially means is that as you are typing code, the editor is analyzing the code to check for warnings and syntax errors. The colored square at the top of the validation sidebar will change color from green (no warnings or errors detected) to yellow (warnings detected) and red (errors have been detected). Clicking on this square will display a popup containing a summary of the issues found with the code in the editor as illustrated in Figure 7-2:
Figure 7-2
The sidebar also displays markers at the locations where issues have been detected using the same color coding. Hovering the mouse pointer over a marker when the line of code is visible in the editor area will display a popup containing a description of the issue (Figure 7-3):
Figure 7-3
Hovering the mouse pointer over a marker for a line of code which is currently scrolled out of the viewing area of the editor will display a “lens” overlay containing the block of code where the problem is located (Figure 7-4) allowing it to be viewed without the necessity to scroll to that location in the editor:
Figure 7-4
It is also worth noting that the lens overlay is not limited to warnings and errors in the sidebar. Hovering over any part of the sidebar will result in a lens appearing containing the code present at that location within the source file.
Having provided an overview of the elements that comprise the Android Studio editor, the remainder of this chapter will explore the key features of the editing environment in more detail.
Splitting the Editor Window
By default, the editor will display a single panel showing the content of the currently selected file. A particularly useful feature when working simultaneously with multiple source code files is the ability to split the editor into multiple panes. To split the editor, right-click on a file tab within the editor window and select either the Split Vertically or Split Horizontally menu option. Figure 7-5, for example, shows the splitter in action with the editor split into three panels:
Figure 7-5
The orientation of a split panel may be changed at any time by right clicking on the corresponding tab and selecting the Change Splitter Orientation menu option. Repeat these steps to unsplit a single panel, this time selecting the Unsplit option from the menu. All of the split panels may be removed by right-clicking on any tab and selecting the Unsplit All menu option.
Window splitting may be used to display different files, or to provide multiple windows onto the same file, allowing different areas of the same file to be viewed and edited concurrently.
Code Completion
The Android Studio editor has a considerable amount of built-in knowledge of Java programming syntax and the classes and methods that make up the Android SDK, as well as knowledge of your own code base. As code is typed, the editor scans what is being typed and, where appropriate, makes suggestions with regard to what might be needed to complete a statement or reference. When a completion suggestion is detected by the editor, a panel will appear containing a list of suggestions. In Figure 7-6, for example, the editor is suggesting possibilities for the beginning of a String declaration:
Figure 7-6
Completion suggestions can be manually invoked using the Ctrl-Space keyboard sequence. This can be useful when changing a word or declaration in the editor. When the cursor is positioned over a word in the editor, that word will automatically highlight. Pressing Ctrl-Space will display a list of alternate suggestions. To replace the current word with the currently highlighted item in the suggestion list, simply press the Tab key.
In addition to the real-time auto completion feature, the Android Studio editor also offers a system referred to as Smart Completion. Smart completion is invoked using the Shift-Ctrl-Space keyboard sequence and, when selected, will provide more detailed suggestions based on the current context of the code. Pressing the Shift-Ctrl-Space shortcut sequence a second time will provide more suggestions from a wider range of possibilities.
Code completion can be a matter of personal preference for many programmers. In recognition of this fact, Android Studio provides a high level of control over the auto completion settings. These can be viewed and modified by selecting the File -> Settings… menu option and choosing Editor -> Code Completion from the IDE Settings section of the settings panel as shown in Figure 7-7:
Figure 7-7
Statement Completion
Another form of auto completion provided by the Android Studio editor is statement completion. This can be used to automatically fill out the parentheses and braces for items such as methods and loop statements. Statement completion is invoked using the Shift-Ctrl-Enter (Shift-Cmd-Enter on Mac OS X) keyboard sequence. Consider for example the following code:
protected void myMethod()
Having typed this code into the editor, triggering statement completion will cause the editor to automatically add the braces to the method:
protected void myMethod() { }
Parameter Information
It is also possible to ask the editor to provide information about the argument parameters accepted by a method. With the cursor positioned between the brackets of a method call, the Ctrl-P (Cmd-P on Mac OS X) keyboard sequence will display the parameters known to be accepted by that method, with the most likely suggestion highlighted in bold:
Figure 7-8
Code Generation
Figure 7-9
For the purposes of an example, consider a situation where we want to be notified when an Activity in our project is about to be destroyed by the operating system. As will be outlined in a later chapter of this book, this can be achieved by overriding the onStop() lifecycle method of the Activity superclass. To have Android Studio generate a stub method for this, simply select the Override Methods… option from the code generation list and select the onStop() method from the resulting list of available methods:
Figure 7-10
Having selected the method to override, clicking on OK will generate the stub method at the current cursor location in the Java source file as follows:
@Override protected void onStop() { super.onStop(); }
Code Folding
Once a source code file reaches a certain size, even the most carefully formatted and well organized code can become overwhelming and difficult to navigate. Android Studio takes the view that it is not always necessary to have the content of every code block visible at all times. Code navigation can be made easier through the use of the code folding feature of the Android Studio editor. Code folding is controlled using markers appearing in the editor gutter at the beginning and end of each block of code in a source file. Figure 7-11, for example, highlights the start and end markers for a method declaration which is not currently folded:
Figure 7-11
Clicking on either of these markers will fold the statement such that only the signature line is visible as shown in Figure 7-12:
Figure 7-12
To unfold a collapsed section of code, simply click on the ‘+’ marker in the editor gutter. To see the hidden code without unfolding it, hover the mouse pointer over the “{…}” indicator as shown in Figure 7-13. The editor will then display the lens overlay containing the folded code block:
Figure 7-13
All of the code blocks in a file may be folded or unfolded using the Ctrl-Shift-Plus and Ctrl-Shift-Minus keyboard sequences.
By default, the Android Studio editor will automatically fold some code when a source file is opened. To configure the conditions under which this happens, select File -> Settings… and choose the Editor -> Code Folding entry listed under IDE Settings in the resulting settings panel (Figure 7-14):
Figure 7-14
Quick Documentation Lookup
Context sensitive Java and Android documentation can be accessed by placing the cursor over the declaration for which documentation is required and pressing the Ctrl-Q keyboard shortcut (Ctrl-J on Mac OS X). This will display a popup containing the relevant reference documentation for the item. Figure 7-15, for example, shows the documentation for the Android Menu class.
Figure 7-15
Once displayed, the documentation popup can be moved around the screen as needed. Clicking on the push pin icon located in the right hand corner of the popup title bar will ensure that the popup remains visible once focus moves back to the editor, leaving the documentation visible as a reference while typing code.
Code Reformatting
In general, the Android Studio editor will automatically format code in terms of indenting, spacing and nesting of statements and code blocks as they are added. In situations where lines of code need to be reformatted (a common occurrence, for example, when cutting and pasting sample code from a web site), the editor provides a source code reformatting feature which, when selected, will automatically reformat code to match the prevailing code style.
To reformat source code, press the Ctrl-Alt-L keyboard shortcut sequence to display the Reformat Code dialog (Figure 7-16). This dialog provides the option to reformat only the currently selected code, the entire source file currently active in the editor or all files in a given project folder.
Figure 7-16
The full range of code style preferences can be changed from within the project settings dialog. Select the File -> Settings menu option and choose Code Style listed under Project Settings in the left hand panel to access a list of supported programming and markup languages. Selecting a language will provide access to a vast array of formatting style options, all which may be modified from the Android Studio default to match your preferred code style.
Summary
The Android Studio editor goes to great length to reduce the amount of typing needed to write code and to make that code easier to read and navigate. In this chapter we have covered a number of the key editor features including code completion, code generation, editor window splitting, code folding, reformatting and documentation lookup.
Previous | Table of Contents | Next |
Testing Android Studio Apps on a Physical Android Device | An Overview of the Android Architecture |