Android Studio is based on JetBrains IntelliJ software (http://www.jetbrains.com/idea) that is the official Integrated Development Environment (IDE) for creating Android apps for Windows, Mac OS X and Linux. There are two versions:
Community Edition (free version)
Ultimate Edition (paid version) that includes additional tools for working with JavaScript, Java Enterprise Edition (JEE) apps and databases
It includes the following features:
Android JAR file (app framework classes)
WYSIWYG editor for multiple screen sizes and resolutions and orientation
Templates to create common layouts (e.g., Login, Master/Detail)
Gradle-based build system to customize building of apps for multiple APKs
Lint inspection tool to check for performance, usability, etc.
ProGuard tool to minimized app size (by removing unused code) and obfuscate code (by renaming classes, fields and methods with obscure names). NO LONGER NEEDED WITH ANDROID STUDIO 2.0.
App signing capability
Documentation
Samples
Android Versions
Android versions are in alphabetical order and are based on some type of confectionery-themed code name starting with Cupcake. The earlier versions 1.0 and 1.1 were not released under specific code names — Wikipedia
Project Templates – Use as a starting template for a given project
ALT + ENTER – Quick Fix for many code completion and remediation
SHIFT + SHIFT – Search for anything especially files
Refactoring – Replace, move, delete or update code in multiple places all at once
Live Templates – expand code from shortcuts
Menu Maker – create menu code with UI interface
Icon Maker – create various density icons from with Android Studio easily
Generate Tool – create code automatically for classes after fields have been defined (e.g., constructor(s), getters/setters, toString method, etc.)
Constraint Layout – to not have to rely of fragment
RecycleView – to not have to rely on the ListView or the GridView
XML markup – use XML markup instead of Java code whenever you can
ALT + click a link – to go to the file
Keyboard Shortcuts (Delete and consolidate with tables below)
Below is a list of "vital few" shortcuts that will make you more productive when using Android Studio.
TIP: To learn all of Android Studio keyboard shortcuts go to Help > Default Keymap Reference. If you don't like the default keyboard options, you can change it by selecting Settings (PC) or Preferences (Mac) and select Keymap. To change them, you need to click on the Copy button, make changes and then click the OK button.
[NEED TO BE CLEAN UP]
On the Mac, replace ALT key with OPT key and CTRL key with CMD key unless otherwise stated.
SHIFT key twice—to open the Search Everywhere feature of Android Studio and type a search word (e.g., MainActivity).
ENTER or TAB—to autocomplete code. (e.g., Start typing a class and then press ENTER or TAB to auto-complete the class name. If the class is in a different package, it will automatically import the package at the top of the code.
CTRL + SHIFT + SPACEBAR—to show the various type of constructor assigned to the class.
CTRL + SHIFT + ENTER—to complete a statement with a semicolon.
SHIFT + ALT + UP ARROW or DOWN ARROW—to MOVE a line of code up or down.
SHIFT + CMD + UP ARROW or DOWN ARROW—to MOVE a complete statement up or down.
CTRL and click on a method or a resource - open method or resource file.
ALT+1 (PC) or CMD+1 (Mac)—to open the Project Window.
CTRL+ALT+L—reformat code to make is easier to read.
CTRL+ALT+T—surround with programming constructs (if/else, while, catch/try, do/while, etc.).
Click on a resource id (e.g., @style/ID) to open its file.
CTRL+D—copy and duplicate code repeatily below existing selected code.
CTRL+Y (PC) or CMD+BACKSPACE (MAC)—cut selected code.
CTRL+J—jump to documentation for a class, etc.
CTRL+Spacebar—bring back up Auto-complete if it has disappear AND shows documentation.
CTRL+/——to comment or uncomment selected line(s) of code with single line comments (e.g., //)
CTRL+SHIFT+/—to comment or uncomment selected line(s) of code with block comment (e.g., /* ... */).
CTRL+SHIFT+J—add a Javadoc comment to a method or a class
ALT+ENTER and click on a string and then enter a resource name - convert a string (e.g., Hello, World) to a string resource (e.g., @string/resource_name).
CTTL+6—to open the logcat panel.
Double-click on tab to view full screen of panel.
Ctrl+P—brings up a list of valid parameters for a constructor when the cursor is in between a blank construdtor parenthesis.
F2/Shift+F2—jump between highlighted syntax errors.
Alt+Up and Alt+DOWN ARROW keys—to quickly move between methods.
Keyboard Shortcuts
Windows/Linux
CMD + SHIFT + RETURN—to complete a statement with a semicolon.
CTRL+SHIFT+A—Command look up
ALT+ENTER—Quick Fix
CTRL+ALT+L—Reformat code
CTRL+Q—Show documents
CTRL+P—Show method parents
ALT+INSERT— Generate method
F4—Jump to source
CTRL+Y—Delete line
CTRL+ALT+SHIFT+N—Search for symbol
CTRL+F9—Build
SHIFT+F10—Build and run
ALT+1—Toggle project visibility
ALT+LEFT ARROW or ALT+RIGHT ARROW—navigate open tabs
ALT+F8—Evaluate Expression
CTRL+MOUSE CLICK—Drill Down
ALT+INSERT— Generate method
Keyboard Shortcuts
Mac where it differs from Windows/Linux.
TIP: For the most part, on the Mac, the commands are similar; however CMD is replaced for CTRL, OPTION is replaced for ALT.
CTRL+LEFT ARROW or ALT+RIGHT ARROW—navigate open tabs
CMD+MOUSE CLICK—Drill Down
CTRL+SHIFT+ UP_ARROW or DOWN_ARROW—to MOVE a line of code or a complete method. Select it and then press the key combination.
Another View of KeyBoard Shortcuts
General Shortcuts
DESCRIPTION
SHORTCUT
Delete line
CTRL + Y
Safe Delete
ALT + DELETE
Close Active Tab
CTRL +
F4
Build and run
SHIFT + F10
Build
CTRL + F9
All purpose (Meta)Shortcut
CTRL + SHIFT + A
Navigation Shortcuts
DESCRIPTION
SHORTCUT
Reformat code
CTRL + ALT + L
Optimize imports
CTRL + ALT + O
Code Completion
CTRL + SPACE
Issue quick fix
ALT + ENTER
Surround code block
CTRL + ALT + T
Rename and refactor
SHIFT + F6
Line Comment or Uncomment
CTRL +/
Block Comment or Uncomment
CTRL + SHIFT +/
Go to previous/next method
ALT + UP/DOWN
Show parameters for method
CTRL + P
Quick documentation lookup
CTRL + Q
Programming Shortcuts
DESCRIPTION
SHORTCUT
Go to class
CTRL + N
Go to file
CTRL + SHIFT + N
Navigate open tabs
ALT + LEFT-ARROW or ALT + RIGHT-ARROW
Lookup recent files
CTRL + E
Go to line
CTRL + G
Navigate to last edit location
CTRL + SHIFT + BACKSPACE
Go to declaration
CTRL + B
Go to implementation
CTRL + ALT + B
Go to source
F4
Go to super Class
CTRL + U
Show Call hierarchy
CTRL + ALT + H
Search in path/project
CTRL + SHIFT + F
Menu Shortcuts
To reformat code, select Code > Reformat Code…
You can fold (collapse or expand) code by clicking on Code > Folding and choosing one of the options (e.g., Expand, Collapse, Expand Recursively, Collapse Recursively).
View > Enter/Exit Presentation Mode (larger font size but still editable)
Right-click on an editor tab and select Split Vertically/Horizontally (create two instance of view) NOTE: You can make changes in one view while freezing the other view.
Right-click on an editor tab and select Move Right/Down
To move a window:
Click on the gear icon at the top right-corner of the window and then uncheck the Docked Mode
Go back and choose Floating Mode. Now you can move or resize the window.
To return it back, uncheck the Floating Mode and then choose Docked Mode.
You can also move the tab and window by clicking on the gear and selecting Move To and then select a direction (Top, Bottom, Left, or Right).
You can also just drag the tab where you want it to be.
To hide a window, click the hide window icon at the top-right corner of the window.
To restore the windows back to their original settings, select Window > Restore Default Layout. Once you have the windows set up the way you like them, you can select Window > Store Current Layout as Default.
If you are in a *.java file, you can easily get to the related XML file that is associated with it by clicking on the related file icon on the left side of the code view window and you will be immediately taken to the XML file.
Instead of writing the stub for an event handler, you can let Android Studio do it for you.
Create or select an object and add an event handler to. Typically, this is a button:
<Button android:onClick="buttonClickHandler" />|
CAUTION: The event handler will become a Java method so you need to use the correct naming convention.
Press ALT+ENTER key and choose Create onClick event handler for the list of intention action. NOTE: If the project has more than one class, you would see it listed.
If there is only one class, click the OK button; otherwise, select the correct class and then click the OK button.
CHECK POINT: You should see a method is created in the selected class.
public void buttonClickHandler (View view) {
}
Add the necessary code between the curly brace pairs.
public void buttonClickHandler (View view) {
Log.d ("myClassName", "A message here...");
}
Create Classes and Other Components
You can create all kind of components (e.g., Class, Interface) from one menu option:
Choose File > New > Java Class from the menu.
In the Create New Class dialog box that appears, give the component a name and then choose the Kind from the menu: NOTE: It it best practice to start a class with a capital letter (e.g, MyUtilityClass).
Click the OK button to create the component.
CHECK POINT: By default, the class is placed in the main package. If you want to move it to another package:
Right click on the base package and choose New Package.
In the New Package dialog box that appears give package a name and then click the OK button.
Drag-and-drop the newly created class into the new package.
In the Move dialog box that appears, click the Refactor button to move the class and change any code (package declaration) to match the new location.
You can optioanal remove the comments.
Create Class, Getters and Setters
To create a Java class:
Right-click on a package and select New > Java Class and enter a class name.
Select Kind (Class, Interface, Enum, Annotation or Singleton) and then click the OK button.
To creae class stub:
Right-click on a class and select Generate...
Choose what you want to Generate from the list:
Constructor
Getter
Setters
Getters and Setters
equals() and hashCode()
toString()
Override Methods
Copyright NOTE: To create getters and setters, you must first create fields for the class.
EXAMPLE: Create Getters and Setters
You can create a set of getters and setters from a list of private instance variables.
Create a class with a list of instance variables:
public class CustomClass{ private String myString; private int myInteger; private String myString2; }
Position the cursor below the variables and right-click and select Source > Generate Getters and Setters.... from the list.
In the Select Fields To Generate Getters and Setters dialog box that appears, select the fields that you want and then click the OK button.
Create a Method Automatically
You can define a method in one class and have it automatically created in another class. For example, let's say you have define a method name in the MainActivity.java class as highlighted below:
MyUtilityClass utility = new MyUtilityClass(); utility.addNumbers();
CHECK POINT: Since the method addNumbers() does not exist yet, it will be highlighted in red.
Click inside of the addNumbers() method and then press ALT+ENTER and select Create method 'addNumbers'.
CHECK POINT: Notice that the addNumbers() method stub was creaed in the MyUtilityClass.java file and open this file because this is the class it is based on.
public void addNumbers() {
}
Click the ENTER key to accept the default return type (void) and to place the cursor between the curly braces. Now you can populate the method with your own code.
Refactor Code
There are a host of ways to use refactoring in Android Studio that allows you to rename, move and extract code. Most of the tasks can be access by selecting Refactor from the menu and then choosing an option:
Refactor This... (CTRL+ALT+SHIFT+T) This menu item will show all of the options in a list.
Rename... (SHIFT+F6)
Change Signature... (CTRL+F6)
Move... (F6)
Copy... (F5)
Safe Delete...(ALT+DELETE)
and more... TIP: Using a Refactoring option is better than doing a search and replace or a cut and paste of code.
Rename Code
For example, continuing with the code from the previous section:
Place the cursor either in the method declaration in the MyUtilityClasss.java file OR in the MainActivity.java file where it is called and then press SHIFT+F6 and then RENAME the method (e.g., addTwoNumbers) and then press the ENTER key.
CHECK POINT: Notice that the method was rename in both the MainActivity.java and the MyUtilityClass.java file even though it was change in one place.
Click inside of the utility variable and press SHIFT+F6 to RENAME the varaible and you will be presented with several options. myUtilityClass was accepted for this example below:
MyUtilityClass utility = new MyUtilityClass(); utility.addNumbers();
CHECK POINT: You should see that both the declaration and usage reference to the variable have been changed to myUtilityClass even though only one was changed.
MyUtilityClass myUtilityClass = new MyUtilityClass(); myUtilityClass.addTwoNumbers();
Move Code
Beside dragging and dropping a class from one package to another to move it, you can also use the Refactor method to move a package as will be demonstrated in the next step. Continuing with the code from the previous section:
Open the MyUtilityClass.java file and click INSIDE of the MyUtilityClass method and then choose Refactor > Move... In the Move dialog box that appears, change the path where you want the package to be moved to and then click the Refactor button.
CHECK POINT: You should see the package has been move in the Android scope panel. Notice also that the package declaration has been changed at the top of the file and if the package was move into the main package, the import statement will be removed.
Extract code
You can also EXTRACT CODE to other programming constructs as will be demonstrated in the next steps:
Select the line(s) of code that you want to extract from some existing code. See the highlighted code below from the previous example:
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); MyUtilityClass myUtilityClass = new MyUtilityClass(); myUtilityClass.addTwoNumbers(); } }
Right-click and from the menu select Refactor > Extract > Method... (CTRL+ALT+M). In the Extract Method dialog box that appears, give the method a name and then click the OK button.
CHECK POINT: You should see the the line(s) of code has been extracted and placed in a method with the name you gave it and the extracted code was replaced by a method call (e.g., myMethods()).
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myMethod(); }
Live Templates are snippets code that can be created by writing a code shortcut that will be expanded to the complete code stub when you click the TAB or the ENTER key. They are defined in the Preference (Mac) or Settings (Windows) menu under Editor > Live Templates. They are used to speed up your coding and fall in five categories:
Andriod
AndroidComments
AndroidLog
AndroidParcelable
AndroidXML
Below are some fo the Live Templates shortcuts for Android:
Examples:
Type Toast and then press the TAB or the ENTER key:
NOTE: If you have automatic import turned on in the Preferences or Settings, an import statement will be added to the top of the code.
CHECK POINT: You should see the word Toast expand to Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();. Now, you can replace the word MainAcitvity if you need to. If you press the ENTER key, you will be taken to a place in the Live Template (between the double quotes) to give the Toast a string for the Toast message (e.g., "message goes here...).
Move the cursor after a Class declaration and then type const and then press the TAB key and then enter a constant name where the cursor was placed (e.g., MYCONSTANT).
public class MainActivity extends AppCompatActivity { private static final int MYCONSTANT = 331;
CHECK POINT: You should see the word const has been REPLACED with private static final int MYCONSTANT = 331;. Now, if you press the ENTER key, you will see the value of the constant gets updated. That's because the constant value is randomized and it does NOT matter what the value is as long as it is CONSTANT (does NOT change). It is best practice to with a constant with ALL CAPS (eg., MYCONSTANT).
Type logi and then press the TAB or the ENTER key and then complete or change the string to whatever you need it to be.
Log.i(TAG, "onCreate: onCreate was fired");
NOTE: The TAG constant does not exist. You can click inside of it and press ALT+ENTER and then select Create constant field 'TAG" from the menu and then give the constant a string value (e.g., MainActivity).
CHECK POINT: You should see the word logi expands to Log.i(TAG, "onCreate: "); before you changed it.
Create Your Own Live Tempalte
You can review the default Live Templates to see how to create your own. Since setting the text property is a common task that you perform often, it may be helpful to create a Live Template to speed up writing code.
Give a TextView an id property that will be used later (e.g., myTextView).
Write a code sample of what you want to use as a Live Template. For this example, we will use:
TextView tv = (TextView) findViewById(R.id.myTextview); tv.setText("Set text property for TextView here...");
Select the lines of code and then from the menu select Tools > Save As Live Templates...
In the Live Templates dialog box that appears, give the template an abbreviation and a description and then modify the code by:
Removing all of the instances of android.widget. (including the period)
Deleting the path before the R object
Wraping what you want to be variables with a pair of dollar signs with variable names (e.g., $myVariable$)
Removing space on the second line
NOTE: Notice a user defined template will show up in the user section of the Live Templates dialog box above..
Click the OK button to create the Live Template.
CHECK POINT: Delete the original lines of code and then type the abbreviation tvText in some code and then press the TAB or ENTER key. You should see the abbreviation expands. Press the TAB key and enter the TextView id (e.g., myTextView) and then press the TAB key again and enter a string message for the TextView.
TextView tv = (TextView) findViewById(R.id.myTextView); tv.setText("My text is set here...");
CHECK POINT: Run the app in an emulator and you will see the text that you set appear in the TextView.
TIP: DESIGN VS CODE (TEXT) VIEW
IMPORTANT CONCEPT TO REMEMBER: Whatever original value is CREATED in Design View with XML attributes can be OVERWRITTEN OR CHANGED to a new value in Text (Code) View with Javacode. This is an important concept that you will see as you create more advanced code. For example, you can create STATIC or PLACEHOLDER content in Design view and then REPLACE them at RUNTIME with DYNAMIC content from a data source (e.g., an array, XML, JSON, Database, Java Code, etc.). Content that does not need to be changed can remain at their “design” values at runtime. To demonstrate this:
In the Text View, make note of the id attribute for the TextView component (It should be textView).
Add the following highlighted code in the MainActivity.java file within the onCreate() methodAFTER the setSupportActionBar() method. You can add whatever short text you want within the quotes:
TextView myNewText = (TextView) findViewById(R.id.textView); myNewText.setText("How are you doing?");
CODE EXPLANATION:
-
The TextView myNewText = (TextView) findViewById(R.id.textView); code is used to bind the component of the XML file to the Java file so that it can be used in code.
-
Now that we have a reference (myNewText) to the TextView component from the XML file, we can now use a setText() method to set the text of that view to whatever text we want (In this case, "Howe are you doing?).
CHECK POINT: Run the app in an emulator. You should see that even though the text field “Hello, World” is written in the Design view’s xml file by default. It is DISPLAYED in the emulator with the phrase, “How are you doing?”
TIP: EVALUATING AN EXPRESSION
IMPORTANT CONCEPT TO REMEMBER: While not real useful now, it is important to learn early how to evaluate expressions in your code to see if your code is working as expected. This is done by setting a breakpoint where you want the code to stop and then evaluating an expression in the code:
Set a breakpoint on the findViewById line
Press the Debug button (not the Play button) to run the app in debug mode.
Choose a virtual device from the list and press the OK button.
NOTE: Notice that the app stop executing at the break point.
Copy an expression from the code. In this case, (TextView) findViewById(R.id.textView); NOTE: You will need to add a semicolon to complete the expression.
Then, select Run > Evaluate Expression... or pressALT+F8 to open the Expression Evaluation dialog box and then paste the expression in the Expression text field.
CHECK POINT: Press the Evaluate button. You should see A LOT of the values for that expression with two of them with the phrase "Hello World!" in it. Notice is says, "Hello, World!" instead of "How are you doing?" because that line of code is AFTER the breakpoint so the setText() method has not yet been executed.
Now, type the following expression [((TextView)findViewById(R.id.textView)).getText(); ] and press the Evaluate button again. You should see the a short list of values being displayed along with the "Hello World!" phrase.
Delete both the text field in the XML file and the two lines of code that was added in the Java file.