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. Unsurprisingly, most of a developer’s time spent using Android Studio will typically involve editing code within the editor window.

The modern code editor must go far beyond the 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 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 tool’s key features. Experienced programmers will find that some of these features are common to most code editors today, while a number are unique to this 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 Kotlin source code file loaded:

Figure 8-1

The elements that comprise the editor window can be summarized as follows:

 

You are reading a sample chapter from an old edition of the Android Studio Essentials – Kotlin Edition book.

Purchase the fully updated Android Studio Koala Kotlin Edition of this publication in eBook or Print format.

The full book contains 100 chapters and over 870 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

  • A – Document Tabs – Android Studio can hold multiple files open for editing at anytime. As each file is opened, it is assigned a document tab displaying the file name in the tab bar along the editor window’s top edge. A small drop-down 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 AltRight 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 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 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 Appearance -> Show Line Numbers menu option.
  • C – Code Structure Location – This bar at the bottom of the editor displays the cursor’s current position as it relates to the overall structure of the code. In the following figure, for example, the bar indicates that the convertCurrency method is currently being edited and that this method is contained within the MainActivity class:
Figure 8-2

Double-clicking an element within the bar will move the cursor to the corresponding location within the code file. For example, double-clicking on the convertCurrency entry will move the cursor to the top of the convertCurrency method within the source code. Similarly, clicking on the MainActivity entry displays a list of available code navigation points for selection:

Figure 8-3
  • D – The Editor Area – The main area where the user reviews, enters, and edits the code. 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 called “on-the-fly code analysis”. This essentially means that as you are typing code, the editor analyzes the code to check for warnings and syntax errors. The indicators at the top of the validation sidebar will update in real-time to indicate the number of errors and warnings found as code is added. 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-4:
Figure 8-4

The up and down arrows move between the error locations within the code. A green check mark indicates that no warnings or errors have been detected.

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:

 

You are reading a sample chapter from an old edition of the Android Studio Essentials – Kotlin Edition book.

Purchase the fully updated Android Studio Koala Kotlin Edition of this publication in eBook or Print format.

The full book contains 100 chapters and over 870 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Figure 8-5

Hovering the mouse pointer over a marker for a line of code that 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-6) allowing it to be viewed without the necessity to scroll to that location in the editor:

Figure 8-6

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.

  • F – The Status Bar – Though the status bar is 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. For example, clicking on the line number displays the Go to Line:Column dialog. Use the View -> Appearance -> Status Bar Widgets menu option to add and remove widgets. For example, the Memory Indicator is a helpful widget if you are experiencing performance problems with Android Studio.

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 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 Right or Split Down menu option. Figure 8-7, for example, shows the splitter in action with the editor split into three panels:

Figure 8-7

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 split panels may be removed by right-clicking on any tab and selecting the Unsplit All menu option.

 

You are reading a sample chapter from an old edition of the Android Studio Essentials – Kotlin Edition book.

Purchase the fully updated Android Studio Koala Kotlin Edition of this publication in eBook or Print format.

The full book contains 100 chapters and over 870 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

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 Kotlin 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 the editor detects a completion suggestion, a panel containing a list of suggestions will appear. In Figure 8-8, for example, the editor is suggesting possibilities for the beginning of a String declaration:

Figure 8-8

If none of the auto-completion suggestions are correct, keep typing, and the editor will continue to refine the suggestions where appropriate. To accept the topmost suggestion, 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, 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. Press the Tab key to replace the current word with the highlighted item in the suggestion list.

In addition to the real-time auto-completion feature, the Android Studio editor also offers a Smart Completion system. 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 broader range of possibilities.

 

You are reading a sample chapter from an old edition of the Android Studio Essentials – Kotlin Edition book.

Purchase the fully updated Android Studio Koala Kotlin Edition of this publication in eBook or Print format.

The full book contains 100 chapters and over 870 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

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 opening the Settings dialog and choosing Editor -> General -> Code Completion from the settings panel, as shown in Figure 8-9:

Figure 8-9

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:

fun myMethod()Code language: Kotlin (kotlin)

Having typed this code into the editor, triggering statement completion will cause the editor to add the braces to the method automatically:

fun myMethod() {
 
}Code language: Kotlin (kotlin)

Parameter Information

It is also possible to ask the editor to provide information about the argument parameters a method accepts. 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:

Figure 8-10

Parameter Name Hints

The code editor may be configured to display parameter name hints within method calls. Figure 8-11, for example, highlights the parameter name hints within the calls to the make() and setAction() methods of the Snackbar class:

 

You are reading a sample chapter from an old edition of the Android Studio Essentials – Kotlin Edition book.

Purchase the fully updated Android Studio Koala Kotlin Edition of this publication in eBook or Print format.

The full book contains 100 chapters and over 870 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Figure 8-11

The settings for this mode may be configured by opening the Settings dialog and navigating to Editor -> Inlay Hints -> Kotlin in the side panel. Turn on or off the Parameter names option on the resulting screen for your chosen programming language. To adjust the hint settings, click on the Exclude list… link 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-12 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.

Figure 8-12

For 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 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, select the Override Methods… option from the code generation list and select the onStop() method from the resulting list of available methods:

Figure 8-13

Having selected the method to override, clicking on OK will generate the stub method at the current cursor location in the Kotlin source file as follows:

override fun onStop() {
   super.onStop()
}Code language: Kotlin (kotlin)

Code Folding

Once a source code file reaches a certain size, even the most carefully formatted and well-organized code can become overwhelming and challenging 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 by using the code folding feature of the Android Studio editor. Code folding is controlled using disclosure arrows that appear at the beginning of each code block in a source file when the mouse pointer hovers in the gutter area. Figure 8-14, for example, highlights the disclosure arrow for a method declaration that is not currently folded:

 

You are reading a sample chapter from an old edition of the Android Studio Essentials – Kotlin Edition book.

Purchase the fully updated Android Studio Koala Kotlin Edition of this publication in eBook or Print format.

The full book contains 100 chapters and over 870 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Figure 8-14

Clicking on this marker will fold the statement such that only the signature line is visible, as shown in Figure 8-15:

Figure 8-15

To unfold a collapsed section of code, click on the disclosure arrow in the editor gutter. To see the hidden code without unfolding it, hover the mouse pointer over the “{…}” indicator as shown in Figure 8-16. The editor will then display the lens overlay containing the folded code block:

Figure 8-16

All of the code blocks in a file may be folded or unfolded using the Ctrl-Shift-Plus and Ctrl-Shift-Minus keyboard sequences (Cmd-Shift-Plus and Cmd-Shift-Minus on macOS).

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, navigate to the Editor -> General -> Code Folding entry in the Settings dialog (Figure 8-17):

Figure 8-17

Quick Documentation Lookup

Context-sensitive Kotlin 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-18, for example, shows the documentation for the Android Menu class.

 

You are reading a sample chapter from an old edition of the Android Studio Essentials – Kotlin Edition book.

Purchase the fully updated Android Studio Koala Kotlin Edition of this publication in eBook or Print format.

The full book contains 100 chapters and over 870 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Figure 8-18

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 website), the editor provides a source code reformatting feature which, when selected, will automatically reformat code to match the prevailing code style.

Press the Ctrl-Alt-L (Cmd-Opt-L on macOS) keyboard shortcut sequence to reformat the source code. To display the Reformat Code dialog (Figure 8-19) use the Ctrl-Alt-Shift-L (Cmd-Opt-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 a result of a source code control update:

Figure 8-19

The full range of code style preferences can be changed by opening the Settings dialog and choosing Code Style in the side 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 Kotlin, and from the Kotlin 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 helpful 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. If sample code is available, the Find Sample Code panel will appear with a list of matching samples. Selecting a sample from the list will load the corresponding code into the right-hand panel.

Live Templates

As you write Android code, you will find that there are common constructs that are used frequently. For example, a common requirement is to display a popup message to the user using the Android Toast class. Live templates are a collection of common code constructs that can be entered into the editor by typing the initial characters followed by a special key (set to the Tab key by default) to insert template code. To experience this in action, type toast in the code editor followed by the Tab key, and Android Studio will insert the following code at the cursor position ready for editing:

 

You are reading a sample chapter from an old edition of the Android Studio Essentials – Kotlin Edition book.

Purchase the fully updated Android Studio Koala Kotlin Edition of this publication in eBook or Print format.

The full book contains 100 chapters and over 870 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Toast.makeText(, "", Toast.LENGTH_SHORT).show()Code language: Kotlin (kotlin)

To list and edit existing templates, change the special key, or add your own templates, open the Settings dialog and select Live Templates from the Editor section of the left-hand navigation panel:

Figure 8-20

Add, remove, duplicate, or reset templates using the buttons marked A in Figure 8-21 above. To modify a template, select it from the list (B) and change the settings in the panel marked C.

Summary

The Android Studio editor goes to great lengths to reduce the typing needed to write code and make that code easier to read and navigate. This chapter covered key editor features, including code completion, code generation, editor window splitting, code folding, reformatting, documentation lookup, and live templates.