Android studio find and replace

Android Studio Refactoring Tips #01: Find and Replace

How to easily find and replace keywords in your AndroidStudio or IntelliJ IDEA project

T his article will be the start of a new series of mine. Within this series, I will cover some quick and simple tricks that will help you to refactor and maintain your Android app.

I would like to start by talking about Android Studio’s Find and Replace feature. Since Android Studio is built on top of IntelliJ IDEA, this tip applies to IntelliJ as well, of course.

However, for the sake of simplicity, I will refer to Android Studio for the rest of the article.

Replace in Path

As you probably know, Android Studio provides a very good search tool “Find in Path” that allows you to find keywords over the whole project or within the scope of just a single file or folder.

In addition to the search functionality, the IDE also offers the “Replace in Path” function.

As an example, I will use the project of one of my previous tutorials.

How to use the Android Activity Result API for selecting and taking images

A short introduction to the ActivityResult API pre-built contracts

To open up the “Replace in Path” feature, use the following shortcuts:

You will be prompted with the following dialog:

Search for your keyword

As you can see we have two input fields. The upper one specifies which keyword we want to search for. The lower one defines with which keyword we want to replace it.

Right below the two input fields, we can define the scope of our search. As default, the “In Project” scope is selected. To the right we find three more options to gradually decrease the scope.

The “Scope” setting provides us a drop-down menu that allows us to switch between a scope that for example only contains project files or the currently opened file.

By setting a “File mask” from the top of the dialog, we can specify a specific file type we want to search for. For example, we could type in *.xml to only search for XML files.

In addition, the filter icon to the right of the File mask option allows us to add some more fine-grained filter options to specify the location we want to search in.

If we don’t select any further location filters and set our scope to “ In Project”, a simple search for the keyword “image” could look like the following.

As you can see, our results contain all occurrences that somehow have a match on “image”. It doesn’t matter if it’s written in upper or lower case or if it’s just contained in a word.

To further specify the keyword we want to search for, we can use the filter options to the right within the upper input field.

If you want to match any cases with your keyword, ignoring case sensitivity and whether it’s included or a standalone match, you can use the “ Match case” option.

If you want to search for your keyword exactly as you entered it, use the “ Words” option.

For cases where you want to have more power over your matches, the “ Replace in Path” tool even provides you a “ Regex” option.

Replace your keyword

Now that we know how to fine-grained search our keyword, we take a look at how to replace the found matches.

To replace our matches we have two options. One is the “ Replace All” feature. As the name already implies, by pressing the “Replace All” button, we replace all the matches shown to us in the dialog window.

If we want to have more control over what we replace, we can use the “ Replace” function. This option just replaces the currently selected match from the selection window.

As you may have noticed, at the moment the keyword match is replaced by the exact replacement word you entered.

But what if you want to preserve the case sensitivity of the match? To do so, just activate the “Preserve case” option at the right of the second input field.

If you now replace the keywords, no matter if with the first or the second option, the keywords are case sensitive.

Hint: If you want to learn more about this feature, check out the official IntelliJ IDEA documentation

Conclusion

The Replace in Path feature provides us a very handy feature to easily maintain our project in cases where we want to replace a keyword or even sentences over the whole project or a more fine-grained specified scope.

Читайте также:  Не обновляется dr web для андроид

Even if the tool looks very simple at a first glance, it provides us many useful options to be able to define our search.

I hope you had some takeaways, clap if you liked my article, and follow for more!

Источник

11 Android Studio Shortcuts every Android Developer must know

This is how you may end up if you try and take a shortcut in real life, but it’s not true for the world of software !! Here you are encouraged to take shortcuts like auto complete, code generations, snippets and what not…

A software engineer must know all the shortcuts of the IDE he is using and must have the environment BENT to his will. Given a keyboard he must be able to navigate through the IDE all around. This can increase his productivity manifolds and is also less distracting than shifting to a mouse/touchpad during typing.

As an Android Engineer I can only speak of Android Studio and here I will mention my top 11 most useful Android Studio Shortcuts ( Windows / Mac ):

This is the holy grail of the navigational shortcuts. It’s really simple. Search Android assets, navigate to the Gradle files, image resources, layouts, colors.xml and much more. There is nowhere you can’t go with the Double Shift shortcut.

Just press Shift twice and a hovering menu will po2.pup. Something like this :

As you can see I searched for “color” and it presented me with all the file with name color. This is my favorite one and I use it a lot in Android Studio.

More often than not, you’ll not be working with all the project files at once. You would be working on a specific module in a project and will be playing around some specific files of that module. The Android Studio has an option where you can browse the most recently opened files on the go. Just press CTRL + E for windows and Command + E for mac and a list of recently opened files will popup.

So did you forgot what’s the shortcut for a replace action ? You forgot what’s the shortcut for a find action ? CTRL + SHIFT + A got you !! You can find actions such as Replace, Find, Run, Instant Run etc…

I searched for the Run action and it gave me all the run options Android Studio has to offer like running the garbage collector and debug runner.

This option is particularly useful if you want to search for some variable or method names. Many a times it so happens that you have declared a variable in some local code and forgot it’s origin, or you may want to find all the places it has been initialized or assigned some value. Well, android studio makes this very easy. Just press CTRL+ALT+SHIFT+N on Windows or Command+Option+O on Mac and type/guess a part of the variable name. Android studio will present you with a list of all possible options.

It can be time consuming to type out all the boilerplate code such as getters/setters in model classes, toString implementation, Parcelable Implementation and much more. Android Studio does all this for you. Press ALT+Insert on Windows or Command+N on Mac and android studio will list out all the options that are available such as override methods, implement interfaces, toString implementation etc…

Code Generation Android Studio Shortcut

When extending a Fragment or Activity class, you need to override certain methods such as onCreate and onCreateView. Apart from that you can also override lifecycle methods such as onPause, onResume, onDestroy. Android studio generates all this boilerplate code for you. Just press CTRL+O on Windows or Command+O on Mac and you’ll be presented with a list of methods that you can override.

You can see there are hundreds of methods which can be overridden and it is not possible to remember them all. So this shortcut comes in handy during development phase. You can also start typing a part of the name of method you want to override and the list will filter automagically.

If you want to delete the entire line, no need to select using a mouse or pressing backspace for the whole day. Just press CTRL+Y on Windows or Command+Backspace on Mac and you are good to go.

Forgot what all parameters your method requires ? Methods such as rawQuery (for SQLite) use many many parameters which are hard to remember. Here’s where Android Studio comes to the rescue. Just press CTRL+Space on Windows or Command+Space on Mac and you will be presented with a popup of all the variants of a method and the arguments that it expects.

Читайте также:  Fake lay hack android

Basic Completion Android Studio Shortcut

This feature is also demonstrated in the previous image. Notice the popup box in grey. This is the documentation box. Just like that we can view the documentation of a particular method, including the class it extends from and some links to more details. Press CTRL+Q on Windows or Command+J on Mac and the popup box will show up. It requires an active internet connection.

Every developer is familiar with the callback hell, OnClickListeners, Dialog Click Listeners etc… These are anonymous classes that have multitudes of methods that need to be overridden. If you have a large codebase, then looking at such code can be daunting. Android Studio provides this option of collapsing all the blocks of code, just showing the method names so that you can find the method you are looking for easily, or just close out all other distractions and make your IDE look neat!!

To expand or collapse code blocks press CTRL+ +/- on Windows or Command + +/- on Mac. Have a look at the image below. The file looks so neat, showing only the method names :

Collapse/Expand Android Studio Shortcut

Again this is one of the most important shortcut that you can use. No need to manually indent all the nested if blocks or the for loops. Android Studio takes care of all the formatting. Just Press CTRL+ALT+L on Windows or Command+Option+L on Mac. The android studio will reformat all the code for you.

And the good part is that it works for XML layouts as well. It takes care of ordering of the xml attributes and indenting nested layouts in your code so that you focus more on coding and less on figuring out what is nested under what.

So, this was my list of 11 most useful Android Studio Keyboard Shortcuts. These have helped me improve my productivity manifolds and hope it does for you as well.

Don’t forget to follow me on LinkedIn and Quora . If you have any questions or suggestions just drop a comment below and I’ll be happy to help.

Источник

Фрагменты

Существует два основных подхода в использовании фрагментов.

Первый способ основан на замещении родительского контейнера. Создаётся стандартная разметка и в том месте, где будут использоваться фрагменты, размещается контейнер, например, FrameLayout. В коде контейнер замещается фрагментом. При использовании подобного сценария в разметке не используется тег fragment, так как его нельзя менять динамически. Также вам придётся обновлять ActionBar, если он зависит от фрагмента. Здесь показан такой пример.

Второй вариант — используются отдельные разметки для телефонов и планшетов, которые можно разместить в разных папках ресурсов. Например, если в планшете используется двухпанельная разметка с двумя фрагментами на одной активности, мы используем эту же активность для телефона, но подключаем другую разметку, которая содержит один фрагмент. Когда нам нужно переключиться на второй фрагмент, то запускаем вторую активность.

Второй подход является наиболее гибким и в целом предпочтительным способом использования фрагментов. Активность проверяет в каком режиме (свои размеры) он запущен и использует разную разметку из ресурсов. Графически это выглядит следующим образом.

Основные классы

Сами фрагменты наследуются от androidx.fragment.app.Fragment. Существует подклассы фрагментов: ListFragment, DialogFragment, PreferenceFragment, WebViewFragment и др. Не исключено, что число классов будет увеличиваться, например, появился ещё один класс MapFragment.

Для взаимодействия между фрагментами используется класс android.app.FragmentManager — специальный менеджер по фрагментам.

Как в любом офисе, спецманагер не делает работу своими руками, а использует помощников. Например, для транзакций (добавление, удаление, замена) используется класс-помощник android.app.FragmentTransaction.

Для сравнения приведу названия классов из библиотеки совместимости:

  • android.support.v4.app.FragmentActivity
  • android.support.v4.app.Fragment
  • android.support.v4.app.FragmentManager
  • android.support.v4.app.FragmentTransaction

Как видите, разница в одном классе, который я привёл первым. Он используется вместо стандартного Activity, чтобы система поняла, что придётся работать с фрагментами. На данный момент студия создаёт проект на основе ActionBarActivity, который является подклассом FragmentActivity.

В одном приложении нельзя использовать новые фрагменты и фрагменты из библиотеки совместимости.

В 2018 году Гугл объявила фрагменты из пакета androd.app устаревшими. Заменяйте везде на версию из библиотеки совместимости. В 2020 году уже используют пакет androidx.fragment.app.

В версии Support Library 27.1.0 появились новые методы requireActivity() и requireContext(), которые пригодятся при написании кода, когда требуется наличие активности и нужно избежать ошибки на null.

Общий алгоритм работы с фрагментами будет следующим:

У каждого фрагмента должен быть свой класс. Класс наследуется от класса Fragment или схожих классов, о которых говорилось выше. Это похоже на создание новой активности или нового компонента.

Читайте также:  Android перевод с французского

Также, как в активности, вы создаёте различные методы типа onCreate() и т.д. Если фрагмент имеет разметку, то используется метод onCreateView() — считайте его аналогом метода setContentView(), в котором вы подключали разметку активности. При этом метод onCreateView() возвращает объект View, который является корневым элементом разметки фрагмента.

Разметку для фрагмента можно создать программно или декларативно через XML.

Создание разметки для фрагмента ничем не отличается от создания разметки для активности. Вот отрывок кода из метода onCreateView():

Глядя на этот код, вы должные понять, что фрагмент использует разметку из файла res/layout/first_fragment.xml, которая содержит кнопку с идентификатором android:id=»@+id/button_first». Здесь также прослеживается сходство с подключением компонентов в активности. Обратите внимание, что перед методом findViewById() используется view, так как этот метод относится к компоненту, а не к активности, как мы обычно делали в программах, когда просто опускали имя активности. Т.е. в нашем случае мы ищем ссылку на кнопку не среди разметки активности, а внутри разметки самого фрагмента.

Нужно помнить, что в методе inflate() последний параметр должен иметь значение false в большинстве случаев.

FragmentManager

Класс FragmentManager имеет два метода, позволяющих найти фрагмент, который связан с активностью:

findFragmentById(int id) Находит фрагмент по идентификатору findFragmentByTag(String tag) Находит фрагмент по заданному тегу

Методы транзакции

Мы уже использовали некоторые методы класса FragmentTransaction. Познакомимся с ними поближе

add() Добавляет фрагмент к активности remove() Удаляет фрагмент из активности replace() Заменяет один фрагмент на другой hide() Прячет фрагмент (делает невидимым на экране) show() Выводит скрытый фрагмент на экран detach() (API 13) Отсоединяет фрагмент от графического интерфейса, но экземпляр класса сохраняется attach() (API 13) Присоединяет фрагмент, который был отсоединён методом detach()

Методы remove(), replace(), detach(), attach() не применимы к статичным фрагментам.

Перед началом транзакции нужно получить экземпляр FragmentTransaction через метод FragmentManager.beginTransaction(). Далее вызываются различные методы для управления фрагментами.

В конце любой транзакции, которая может состоять из цепочки вышеперечисленных методов, следует вызвать метод commit().

Аргументы фрагмента

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

  • Активность может создать фрагмент и установить аргументы для него
  • Активность может вызвать методы экземпляра фрагмента
  • Фрагмент может реализовать интерфейс, который будет использован в активности в виде слушателя

Фрагмент должен иметь только один пустой конструктор без аргументов. Но можно создать статический newInstance с аргументами через метод setArguments().

Доступ к аргументам можно получить в методе onCreate() фрагмента:

Динамически загружаем фрагмент в активность.

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

Вызываем метод в активности:

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

Управление стеком фрагментов

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

Чтобы добавить транзакцию в стек, вызовите метод FragmentTransaction.addToBackStack(String) перед завершением транзакции (commit). Строковый аргумент — опциональное имя для идентификации стека или null. Класс FragmentManager имеет метод popBackStack(), возвращающий предыдущее состояние стека по этому имени.

Если вы вызовете метод addToBackStack() при удалении или замещении фрагмента, то будут вызваны методы фрагмента onPause(), onStop(), onDestroyView().

Когда пользователь нажимает на кнопку возврата, то вызываются методы фрагмента onCreateView(), onActivityCreated(), onStart() и onResume().

Рассмотрим пример реагирования на кнопку Back в фрагменте без использования стека. Активность имеет метод onBackPressed(), который реагирует на нажатие кнопки. Мы можем в этом методе сослаться на нужный фрагмент и вызвать метод фрагмента.

Теперь в классе фрагмента прописываем метод с нужным кодом.

Более желательным вариантом является использование интерфейсов. В некоторых примерах с фрагментами такой приём используется.

Интеграция Action Bar/Options Menu

Фрагменты могут добавлять свои элементы в панель действий или меню активности. Сначала вы должны вызвать метод Fragment.setHasOptionsMenu() в методе фрагмента onCreate(). Затем нужно задать настройки для методов фрагмента onCreateOptionsMenu() и onOptionsItemSelected(), а также при необходимости для методов onPrepareOptionsMenu(), onOptionsMenuClosed(), onDestroyOptionsMenu(). Работа методов фрагмента ничем не отличается от аналогичных методов для активности.

В активности, которая содержит фрагмент, данные методы автоматически сработают.

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

Код для активности:

Код для фрагмента:

Связь между фрагментом и активностью

Экземпляр фрагмента связан с активностью. Активность может вызывать методы фрагмента через ссылку на объект фрагмента. Доступ к фрагменту можно получить через методы findFragmentById() или findFragmentByTag().

Источник

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