How to code android studio

Редактор кода

Рассмотрим возможности редактора кода при написании приложений.

Инъекция языка

Студия позволяет делать инъекцию в существующий код. Что это такое? Например, JSON имеет свой формат данных. Если писать код вручную в данном формате, то можно столкнуться с неудобствами — вам приходится экранировать символы в большом фрагменте кода. Студия поможет нам. Создадим переменную jsonString:

Помещаем курсор между кавычками и нажимаем комбинацию Alt + Enter , выбираем пункт Inject language or reference, в выпадающем списке выбираем JSON (JSON files).

Далее следует ещё раз нажать комбинацию Alt + Enter , чтобы инъекция была постоянной. Студия добавит комментарий к переменной.

Если вы скопируете текст в формате JSON и вставите его между кавычками, то экранирование произойдёт автоматически.

Сам текст не обязательно копировать из другого источника, можете создавать JSON-запись в самой студии. Снова нажимаем Alt + Enter и выбираем пункт Edit JSON Fragment. Появится новая панель, в котором вы можете набирать текст, а в редакторе кода будет выводиться валидный код для работы.

Аналогично можно работать с регулярным выражением.

Перемещаем метод вверх или вниз

Иногда хочется для лучшей читаемости поменять местами методы в коде. Вырезать и вставлять в новое место слишком утомительно. Есть способ лучше. Установите указатель мыши на имени метода и нажмите комбинацию Ctrl+Shift+Стрелка_Вверх — метод автоматически перепрыгнет через метод над собой. Как переместить вниз вы сами догадаетесь.

Сворачиваем фрагменты кода

Студия умеет сворачивать фрагменты кода, которые являются структурной единицей, например, метод. Щёлкнув по фиговине (как это называется?), вы убираете код, чтобы не мозолил вам глаза.

Но мало кто знает, что свернуть можно любой свой код. Для этого ставим два слеша, как в комментариях, а затем добавляем слово region (без пробела) и через пробел название блока. Это будет началом блока. Конец блока обозначаем через //endregion

Теперь отмеченный блок можно сворачивать. Наведите порядок у себя в коде.

Редактор кода для XML в режиме Text

[I18N] Hardcoded string

Когда вы редактируете код разметки экрана активности, то можете встретить предупреждение [I18N] Hardcoded string «Какой-то ваш текст», should use @string resource.

Студия информирует вас о возможной проблеме, если вы в будущем задумаетесь о локализации приложения. Странное выражение I18N переводится очень просто. Здесь зашифровано слово INTERNATIONALIZATION — первая буква I, последняя буква N и восемнадцать букв между ними.

Вам нужно заменить свой жёстко закодированный текст на строковый ресурс. Установите курсор внутри текста, нажмите комбинацию клавиш Alt+Enter и выберите пункт Extract string resource. Далее в диалоговом окне придумываете имя для ресурса и выбираете файл для хранения (обычно, strings.xml).

Предположим, вы заменили везде текст на строковые ресурсы и решили отредактировать текст у кнопки. Снова ставим курсор на нужном тексте и нажимаем комбинацию клавиш Ctrl+B, у вас сразу откроется файл strings.xml и не надо его искать в дереве проекта.

Ещё один приём — если вы хотите видеть вместо кода android:text=»@string/click» реальный текст из ресурса, то нажмите комбинацию Ctrl+- (клавиша минус на цифровой клавиатуре) и он подтянется.

Вкладки

Каждый файл проекта открывается в собственной вкладке. Вкладки можно менять местами перетаскиванием с помощью мыши. Переключаться можно через клавиши Alt-стрелка влево и Alt-стрелка вправо. Также можно вызвать Switcher с помощью комбинации Ctrl+Tab.

Если будет открыто слишком много вкладок, то часть из них сгруппируется и будет доступна через выпадающий список по нажатию на треугольник.

Если имя файла на вкладке подчёркнуто красной волнистой линией, значит в коде содержится ошибка и не нужно запускать программы, то время потеряете. Сначала исправьте ошибку.

Вкладку можно «отстегнуть». Нажмите на вкладку и удерживая мышку, перетащите вкладку на рабочий стол. Также её можно вернуть обратно.

Каждая вкладка имеет контекстное меню и значок для закрытия. Изучите пункты меню самостоятельно. Например, можно разбить редактор кода на две части (по вертикали или горизонтали), чтобы видеть разные участки кода одновременно.

Строка состояния

В нижней части студии находится строка состояния. В нижнем правом углу имеется текстовая метка с информацией о текущем местоположении курсора в документе (номер строки:номер символа). Если подвести мышку к надписи, то можно увидеть всплывающую подсказку Click to go to line. Щелчок вызовет диалоговое окно для быстрого перехода на нужную позицию.

Рядом также имеется текстовая метка с указанием кодировки, в которой пишется код. В последних версиях студии это стало проблемой для русскоязычных программистов. Студия может использовать системную кодировку, которая часто бывает windows-1551, но в Android принято использовать UTF-8, и после запуска приложения вместо текста можно увидеть кракозябры.

Остальные элементы не представляют интереса.

Информационный желоб

Слева от редактора кода имеется отдельная полоска, которую я назвал информационным желобом. На ней можно увидеть различные значки. Например, у класса MainActivity выводится значок, связанный XML-разметкой для данного класса. Нажав на него, вы можете быстро открыть нужный XML-файл.

Читайте также:  Прокси сервер вручную андроид как настроить

Также выводятся значки для методов. Каждый тип методов имеет свой цвет.

В данном желобе устанавливаются точки останова (breakpoint).

Доступно контекстное меню. Например, можно выбрать показ номеров строки.

На границе желоба и редактора кода имеются маркеры для сворачивания блоков кода.

Если нажать клавишу F11, то текущая строка будет помечена как закладка и появится галочка.

Анализ кода

Справа от редактора кода находится анализатор кода. Если код содержит ошибки, сверху будет гореть красный прямоугольник. Если ошибок нет, но есть предупреждения, то будет гореть жёлтый прямоугольник. При правильном коде горит зелёный прямоугольник.

В случае ошибок или предупреждений также выводятся зарубки. Если подвести к ним курсор мыши, то можно прочитать сообщение или сразу перейти в нужную строку для исправления, нажав на неё. Также есть синие зарубки для выделенных слов и задач TODO.

Автодополнение кода

Студия поддерживает автодополнение кода, когда по первым символам подставляет нужные слова. Распространяться на эту тему не буду.

Основная комбинация Ctrl+Space.

Если написать имя метода, например, «private void onClick()» и нажать комбинацию Ctrl+Shift+Enter, то студия сгенерирует фигурные скобки.

Когда у вас есть кусок кода и вы начинаете исправлять его, то возникает следующая ситуация. Студия предлагает подсказку, вы соглашаетесь и нажимаете Enter.

В данном случае мы хотим заменить переменную name на catName, но если нажмём на Enter, то подсказка присоединится к старому коду и мы получим catNamename. В следующий раз нажимайте на клавишу Tab и тогда старый вариант заменится на новый.

Также изучите другие клавиатурные комбинации.

Периодически используйте команды меню Code: Reformat Code и Rearrange Code. Первая команда полезна для Java-кода, а вторая для XML-разметки. Код станет аккуратнее.

Перевод на новую строку

Если курсор находится в середине выражения и вы хотите начать новую строку, не обязательно гнать курсор в конец строки. Просто нажмите комбинацию Shift+Enter.

Источник

Getting Started With Android Studio

Android Studio is a fairly new IDE (Integrated Development Environment) made available for free by Google to Android developers. Android Studio is based on IntelliJ IDEA, an IDE that also offers a good Android development environment. In this tutorial, I’ll show you how to create a new Android project and take advantage of the features that Android Studio has to offer.

When you’re just getting started with Android Studio, it can be very helpful to use an Android app template. You can find over a thousand of them for sale on Envato Market:

Android app templates for sale on Envato Market

1. Project Setup

Before you start exploring Android Studio, you’ll first need to download and install it. Note that you need to have JDK 6 or higher installed. If you’re on Windows, launch the .exe file and follow the steps of the setup wizard. If you’re running OS X, mount the disk image by double-clicking it and drag Android Studio to your Applications folder.

If you’ve successfully completed the above steps, then your development environment should be set up correctly. You’re now ready to create your first Android application using Android Studio. When you launch Android Studio for the first time, you should be presented with a welcome screen, offering you a number of choices to get you started.

In this tutorial, we’re going to choose the New Project option. However, you can choose Import Project if you’d like to import a project from, for example, Eclipse, into Android Studio. Android Studio will convert the Eclipse project to an Android Studio project, adding the necessary configuration files for you.

If you select Open Project from the list of options, you can open projects created with either Android Studio or IntelliJ IDEA. By choosing Check out from Version Control, you can check out a copy of a project that’s under version control. This is a great way to quickly get up to speed with an existing project.

To get us started, choose New Project from the list of options. This will show you a list of options to configure your new project. In this tutorial, we’re going to create a simple application to show you some of Android Studio’s most important features. I’m sure you agree that there’s no better name for our project than HelloWorld.

As you can see in the above screenshot, I’ve named my application HelloWorld and set the module name to HelloWorld. If you’re unfamiliar with IntelliJ IDEA, you may be wondering what a module is. A module is a discrete unit of functionality that can be compiled, run, tested, and debugged independently. Modules contain source code, build scripts, and everything else required for their specific task.

When creating a new project, you can also set the package name of the project. By default, Android Studio sets the last element of the project’s package name to the name of the module, but you can change it to whatever you want.

The other settings are the project’s location on your machine, the minimum and target SDK, the SDK your project will be compiled with, and the project’s theme. You can also tell Android Studio to create an Activity class and a custom launch icon for you, and whether the project supports GridLayout, Fragments, a Navigation Drawer, or an Action Bar.

Читайте также:  Самые покупаемые андроид смартфоны

We won’t create a custom icon for this application so you can uncheck the checkbox labeled Create custom launch icon. Click Next to continue setting up your project.

Because we checked the checkbox Create activity in the previous step, you are asked to configure the Activity class Android Studio will create for you.

Since we’ll be starting with a blank Activity class, you can click Next to proceed to the next step in the setup process in which you’re asked to name the Activity class, the main layout, and the fragment layout. You can also set the navigation type, which we’ll leave at None for this project. Take a look at the next screenshot to see what your settings should look like.

After clicking Finish, you’ll be presented with Android Studio’s user interface with the project explorer on the left and the workspace on the right. With your project set up in Android Studio, it’s time to explore some of the key features of Android Studio.

2. Android Virtual Devices

An Android Virtual Device or AVD is an emulator configuration, allowing you to model an Android device. This makes running and testing applications on a wide range of devices much easier. With an Android Virtual Device, you can specify the hardware and software the Android Emulator needs to emulate.

The preferred way to create an Android Virtual Device is through the AVD Manager, which you can access in Android Studio by selecting Android > AVD Manager from the Tools menu.

If you’re development environment is set up correctly, the Android Virtual Device Manager should look similar to the screenshot below.

To create a new AVD, click New. on the right, give the AVD a name, and configure the virtual device as shown below. Click OK to create your first AVD.

To use your newly created AVD, select it from the list in the AVD manager, and click Start. on the right. If your AVD is set up correctly, the Android Emulator should launch as shown in the screenshot below.

With the Android Emulator up and running, it’s time to launch your application by selecting Run ‘helloworld’ from the Run menu. That’s how easy it is to run an application in the Android Emulator.

3. Live Layout

Android Studio’s live layout feature lets you preview your application’s user interface without the need to run it on a device or the emulator. The live layout feature is a powerful tool that will literally save you hours. Viewing your application’s user interface is much faster using live layouts.

To work with live layouts, double-click the XML layout file and select the Text tab at the bottom of the workspace. Select the Preview tab on the right of the workspace to preview the current layout. Any changes you make to the XML layout will be reflected in the preview on the right. Take a look at the screenshot below to get a better idea of this neat feature.

There are a number of other advantages of the live layout feature that are worth pointing out. You can, for example, create a variation of the XML layout you’re currently working on by selecting an option from the first menu in the Preview pane. You can, for example, create separate views for portrait and landscape and Android Studio will create the necessary folders and files for you.

The second menu in the Preview pane lets you change the size of the device shown in the Preview pane. The third menu lets you change the orientation of the device shown in the Preview pane, which makes it easy to see how a layout looks in different orientations and using different themes.

The fourth menu in the Preview pane gives you easy access to the Activity or fragment in which the layout is used. The Preview pane also lets you change the language used in the live layout to make it easy to preview a layout in different languages. The rightmost menu lets you change the API version.

The Preview pane also includes controls to zoom in on the layout, refresh the Preview pane, or take a screenshot.

4. Templates

Android Studio provides developers with a number of templates to speed up development. These templates automatically create an Activity and the necessary XML files. You can use these templates to create a basic Android application, which you can then run on a device or in the emulator.

With Android Studio, you can create a template when you create a new Activity . Right-click on the package name in the project navigator on the left, select New from the menu, and choose Activity from the list of options. Android Studio then shows you a list of templates, such as Blank Activity, Fullscreen Activity, and Tabbed Activity.

Читайте также:  Santa claus in trouble android

You can also select Image Asset from the menu, which will launch a wizard that guides you through the creation process. Let me show you how to create a new Activity based on the Login Activity template. Select the Login Activity option from the list of Activity templates to fire up the wizard.

As you can see in the above screenshot, I’ve named the Activity LoginActivity, set the Layout Name to activity_login, given the Activity a title of Sign In. The checkbox labeled Include Google+ sign in is checked by default. Uncheck it since we won’t be using this feature in our example.

You can optionally set the Hierarchical Parent of the new Activity . This will let you navigate back if you tap the device’s back button. We will leave this field empty. After clicking Finish, Android Studio creates the necessary files and folders for you. If all went well, you should see a new Activity and Layout in your project.

The next step is to set up the new Activity in the manifest file so it’s used as the main Activity when the application launches. As you can see in manifest file below, the LoginActivity class has its own activity node.

To make your application launch the LoginActivity you created, remove the activity node for the LoginActivity class and replace com.tuts.HelloWorld.MainActivity
with com.tuts.HelloWorld.LoginActivity . The result is that the application will now use the LoginActivity class as its main Activity .

When you build and run your application in the emulator, you should see a screen similar to the one shown below. This means that we’ve successfully replaced the blank Activity class with the newly created LoginActivity class.

5. Lint Tools

Testing your code is one thing, but it’s equally important to apply best practices when writing code. This will improve performance and the overall stability of your application. It’s also much easier to maintain a properly structured project.

Android Studio’s includes Android Lint, a static analyzer that analyzes your project’s source code. It can detect potential bugs and other problems in your code that are the compiler may overlook.

The below screenshot, for example, tells us that the LinearLayout in this layout is of no use. The nice thing about Android Lint is that it gives you a reason for the warning or error, which makes it easier to fix or resolve.

It’s good practice to run Android Studio’s lint tool from time to time to check your project for potential problems. The lint tool will even tell you if you have duplicate images or translations.

To run the lint tool, select Inspect Code… from the Analyze menu in Android Studio to start the process. When Android Studio has finished inspect your project, it will present you with the results at the bottom of the window. Note that in addition to Android Lint, Android Studio performs a number of other checks as well. Simply double-click an issue to navigate to the file in which the problem is located.

6. Rich Layout Editor

Android Studio has a rich layout editor in which you can drag and drop user interface components. You can also preview layouts on multiple screen configurations as we saw earlier in this tutorial.

The rich layout editor is very straightforward to use. We first need a layout to work with. Navigate to the layout folder in your project’s res folder, right-click the layout folder, and select New > Layout resource file from the menu that appears.

Give the new layout a name, set its root element, and click OK. Android Studio will automatically open the layout in the editor on the right.

At the bottom of the editor, you should see two tabs, Design and Text. Clicking the Text tab brings up the editor, allowing you to make changes to the currently selected layout.

Clicking the Design tab brings up another editor that shows you a preview of the layout. To add a widget to the layout, drag it from the list of widgets on the left to the layout on the right. It’s that simple.

Conclusion

In this tutorial, we’ve taken a brief look at some of the key features of Android Studio. It is very similar to IntelliJ IDEA, but it contains a number of important enhancements that make Android development easier, faster, and more enjoyable.

If you want to speed things up even more, try using an Android app template from Envato Market, or working with a freelance Android developer on Envato Studio.

Источник

Оцените статью