Monday, June 10, 2019

Android Studio shortcut to insert a Kotlin logging code using Live Template


Android Studio has a Live Template system for storing predefined code templates which can be recalled via an abbreviation keyword and automatically inserted at the cursor location in the source code editor. This can ease the task of typing in frequently used code syntax.

In this example, a template with the abbreviation logd shall be created which will insert the following code at the cursor location when activated only within a Kotlin language file. Once the code is inserted, the cursor will be placed inside the quotation marks.

Log.d(TAG, "")

Do the following:
  1. In Android Studio, select File | Settings.

    The Settings dialog box appears.
     
  2.  Select Editor | Live Templates.

  3. Then click the + button on the right. Choose Live Template. In the Abbreviation field, type in the keyword, e.g. logd that will activate this template. In the Description field, type in a accurate value e.g. Log debug message.

  4. In the Template text field, type in the code syntax and/or any macro, e.g. Log.d(TAG, "$END$")

    Note: $END$ is a macro which will position the cursor after the template has been inserted.
  5. Next, click Define to choose the environment in which this template can be activated.

  6. In the popup, choose a language or group construct e.g. Kotlin. Click OK

    The template is created.
Now, to use the newly created template, open a Kotlin file in the code editor. Place the cursor on the location in the code and press CTRL-j on the keyboard. A pop up menu with a list of template keywords will appear.



Type in the keyword logd or choose the logd keyword with the mouse and press Enter. The template is inserted and the cursor placed between the quote marks as shown below.

No comments: