- Adding Action Buttons
- This lesson teaches you to
- You should also read
- Specify the Actions in XML
- Download action bar icons
- Add the Actions to the Action Bar
- Respond to Action Buttons
- Add Up Button for Low-level Activities
- How to add Extended Floating Action Button in Android | Android Studio | Java
- Step 1: add the dependency
- Step 2: add the drawable files
- Step 3: design the XML file
- Step 4: add the functionality
- Анимация Floating Action Button в Android
- Floating Action Button
- Меню из FAB’ов
- Buttons
- Responding to Click Events
- Kotlin
- Using an OnClickListener
- Kotlin
- Styling Your Button
- Borderless button
- Custom background
Adding Action Buttons
This lesson teaches you to
You should also read
The action bar allows you to add buttons for the most important action items relating to the app’s current context. Those that appear directly in the action bar with an icon and/or text are known as action buttons. Actions that can’t fit in the action bar or aren’t important enough are hidden in the action overflow.
Specify the Actions in XML
All action buttons and other items available in the action overflow are defined in an XML menu resource. To add actions to the action bar, create a new XML file in your project’s res/menu/ directory.
Add an element for each item you want to include in the action bar. For example:
Download action bar icons
To best match the Android iconography guidelines, you should use icons provided in the Action Bar Icon Pack.
This declares that the Search action should appear as an action button when room is available in the action bar, but the Settings action should always appear in the overflow. (By default, all actions appear in the overflow, but it’s good practice to explicitly declare your design intentions for each action.)
The icon attribute requires a resource ID for an image. The name that follows @drawable/ must be the name of a bitmap image you’ve saved in your project’s res/drawable/ directory. For example, «@drawable/ic_action_search» refers to ic_action_search.png . Likewise, the title attribute uses a string resource that’s defined by an XML file in your project’s res/values/ directory, as discussed in Building a Simple User Interface.
Note: When creating icons and other bitmap images for your app, it’s important that you provide multiple versions that are each optimized for a different screen density. This is discussed more in the lesson about Supporting Different Screens.
If your app is using the Support Library for compatibility on versions as low as Android 2.1, the showAsAction attribute is not available from the android: namespace. Instead this attribute is provided by the Support Library and you must define your own XML namespace and use that namespace as the attribute prefix. (A custom XML namespace should be based on your app name, but it can be any name you want and is only accessible within the scope of the file in which you declare it.) For example:
Add the Actions to the Action Bar
To place the menu items into the action bar, implement the onCreateOptionsMenu() callback method in your activity to inflate the menu resource into the given Menu object. For example:
Respond to Action Buttons
When the user presses one of the action buttons or another item in the action overflow, the system calls your activity’s onOptionsItemSelected() callback method. In your implementation of this method, call getItemId() on the given MenuItem to determine which item was pressed—the returned ID matches the value you declared in the corresponding element’s android:id attribute.
Add Up Button for Low-level Activities
Figure 4. The Up button in Gmail.
All screens in your app that are not the main entrance to your app (activities that are not the «home» screen) should offer the user a way to navigate to the logical parent screen in the app’s hierarchy by pressing the Up button in the action bar.
When running on Android 4.1 (API level 16) or higher, or when using ActionBarActivity from the Support Library, performing Up navigation simply requires that you declare the parent activity in the manifest file and enable the Up button for the action bar.
For example, here’s how you can declare an activity’s parent in the manifest:
Then enable the app icon as the Up button by calling setDisplayHomeAsUpEnabled() :
Because the system now knows MainActivity is the parent activity for DisplayMessageActivity , when the user presses the Up button, the system navigates to the parent activity as appropriate—you do not need to handle the Up button’s event.
For more information about up navigation, see Providing Up Navigation.
Источник
How to add Extended Floating Action Button in Android | Android Studio | Java
How to add Extended Floating Action Button in Android | Android Studio | Java.
In this tutorial, we are going to create an extended floating action button in android. A floating action button (FAB) performs the primary, or most common, action on a screen. It appears in front of all screen content, typically as a circular shape with an icon in its center.
Extended Floating Action Button is the newly introduced class with Material Components library in Android.
Material Components is introduced with SDK 28 or Android P. It’s a superset of Support Design Library with lots of new additions and improvements. And, in this tutorial, we are going to create an extended floating action button.
So, let’s start creating the extended FAB.
Before going to create let’s see what you’re going to see.
Step 1: add the dependency
make sure to add the material design dependency in your build.gradle app file.
Step 2: add the drawable files
before going to design the main XML file, first, import the drawable files. Below drawable files that I used in my project.
Step 3: design the XML file
now, design the main XML file, add the Extended Floating Action Button that is set as the parent FAB and also add the child FAB. Here as a child FAB, I used two FABs.
parent FAB: Action
child FAB 1: Alarm
child FAB 2: Person
Step 4: add the functionality
now in the main JAVA file add the functionality for the extended FAB and add the click listener in the child FAB.
Источник
Анимация Floating Action Button в Android
С момента возникновения концепции Material design одним из самых простых в реализации элементов стала плавающая кнопка действия — FAB, Floating Action Button. Этот элемент быстро обрёл широчайшую популярность среди разработчиков и дизайнеров. В этой публикации мы рассмотрим, как можно анимировать FAB и сделать её интерактивной. Но сначала разберём, как вообще добавить этот элемент в ваш проект.
FAB выглядит как цветной круг в правом нижнем углу экрана. Если в Android Studio создать новый проект Blank Activity, то в нём автоматически будет сгенерирована плавающая кнопка действия.
Floating Action Button
FAB может быть одного из двух размеров: 56 dp (по умолчанию) или 40 dp. Если вы хотите подробнее изучить принципы использования FAB в дизайне приложения, то обратите внимание на официальные гайдлайны Google.
В самых свежих Android-приложениях FAB реагирует на прокручивание списка элементов. Было бы логичнее скрывать её во время прокручивания. Вот что имеется в виду:
Для отображения этой анимации создадим recyclerView , благодаря которому FAB реагирует на прокручивание. Сегодня доступно немало библиотек, позволяющих добиться этого с помощью пары строк кода. Например:
Здесь использован класс FloatingActionButton.Behavior() , чья основная задача, согласно официальной документации, заключается в перемещении видов FloatingActionButton , чтобы ни один из Snackbar их не перекрывал. Но в нашем случае этот класс является расширенным, так что мы можем его использовать для реализации нужного поведения кнопки.
Что же делает данный класс? При каждой инициализации прокрутки вниз метод onStartNestedScroll() возвращает значение true. После этого метод onNestedScroll() отображает или прячет кнопку, в зависимости от её текущей видимости. Конструктор класса FloatingActionButton.Behavior() является важной частью описанного поведения вида (view) и извлекается из XML-файла.
Добавим в FAB атрибут layout_behavior , содержащий название пакета, а в конце — имя класса. Иначе говоря, в атрибуте должно быть указано точное размещение класса в проекте. Например:
Анимация выглядит хорошо, но можно сделать ещё лучше. Например, чтобы кнопка уходила за пределы экрана во время прокрутки — это более реалистичное поведение:
Здесь используется та же логика, что и в предыдущем варианте, за исключением способа исчезновения FAB. Анимация довольно проста. Кнопка уходит вниз с помощью LinearInterpolator. Расстояние, которое ей нужно пройти, равно высоте кнопки плюс ширина нижнего поля.
Обратите внимание, что в выражениях if отсутствуют проверки View.VISIBLE и View.GONE , поскольку в данном случае вид не скрывается, а лишь уплывает за пределы экрана.
Меню из FAB’ов
Существует немало приложений, авторы которых создали красивые и хорошо работающие меню, состоящие из плавающих кнопок действия.
Давайте сделаем нечто подобное. Для начала создадим макет, содержащий три маленькие кнопки. Они невидимы и расположены в самом низу макета, под главной FAB. Содержимое fab_layout.xml:
Этот макет нужно включить в макет activity под главной FAB.
Теперь нужно добавить анимацию исчезновения и появления каждой из малых кнопок.
Примечание: здесь вы можете столкнуться с проблемой, связанной с отработкой нажатия на малые кнопки. Когда анимация завершается, реальное положение кнопки не меняется, перемещается только вид. Поэтому вы не сможете правильно обработать касание кнопки. Для решения этой проблемы можно настроить параметры макетов каждой кнопки с учётом их нового положения, и только потом выполнять анимацию перемещения вида.
Саму анимацию вы можете посмотреть в конце этой публикации. Порядок действий для всех кнопок один и тот же, различаются лишь координаты перемещения.
fab1 перемещается с помощью добавления в layoutParams полей справа и снизу, после чего инициируется анимация.
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) fab1.getLayoutParams();
layoutParams.rightMargin -= (int) (fab1.getWidth() * 1.7);
layoutParams.bottomMargin -= (int) (fab1.getHeight() * 0.25);
fab1.setLayoutParams(layoutParams);
fab1.startAnimation(hide_fab_1);
fab1.setClickable(false);
Процесс скрывания представляет собой обратное воспроизведение предыдущей анимации.
//Анимации одной из малых кнопок
Animation show_fab_1 = AnimationUtils.loadAnimation(getApplication(), R.anim.fab1_show);
Animation hide_fab_1 = AnimationUtils.loadAnimation(getApplication(), R.anim.fab1_hide);
Теперь создадим в папке res/anim/ файлы для каждой из анимаций. Делается это просто, но если у вас возникнут затруднения, то можете обратиться к документации.
Если вы посмотрите на тэг перевода (translate tag), отвечающий за движение вида, то увидите, что коэффициент перемещения (170% и 25%) соответствует коэффициентам, использованным при добавлении полей и извлечённым в Java-код.
Все вышеописанные шаги мы повторяем и для остальных малых кнопок. Различаются только коэффициенты перемещения: fab2 — 150% и 150%, fab3 — 25% и 170%.
Источник
Buttons
A button consists of text or an icon (or both text and an icon) that communicates what action occurs when the user touches it.
Depending on whether you want a button with text, an icon, or both, you can create the button in your layout in three ways:
- With text, using the Button class:
- With an icon, using the ImageButton class:
- With text and an icon, using the Button class with the android:drawableLeft attribute:
Key classes are the following:
Responding to Click Events
When the user clicks a button, the Button object receives an on-click event.
To define the click event handler for a button, add the android:onClick attribute to the element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method.
For example, here’s a layout with a button using android:onClick :
Within the Activity that hosts this layout, the following method handles the click event:
Kotlin
The method you declare in the android:onClick attribute must have a signature exactly as shown above. Specifically, the method must:
- Be public
- Return void
- Define a View as its only parameter (this will be the View that was clicked)
Using an OnClickListener
You can also declare the click event handler programmatically rather than in an XML layout. This might be necessary if you instantiate the Button at runtime or you need to declare the click behavior in a Fragment subclass.
To declare the event handler programmatically, create an View.OnClickListener object and assign it to the button by calling setOnClickListener(View.OnClickListener) . For example:
Kotlin
Styling Your Button
The appearance of your button (background image and font) may vary from one device to another, because devices by different manufacturers often have different default styles for input controls.
You can control exactly how your controls are styled using a theme that you apply to your entire application. For instance, to ensure that all devices running Android 4.0 and higher use the Holo theme in your app, declare android:theme=»@android:style/Theme.Holo» in your manifest’s element. Also read the blog post, Holo Everywhere for information about using the Holo theme while supporting older devices.
To customize individual buttons with a different background, specify the android:background attribute with a drawable or color resource. Alternatively, you can apply a style for the button, which works in a manner similar to HTML styles to define multiple style properties such as the background, font, size, and others. For more information about applying styles, see Styles and Themes.
Borderless button
One design that can be useful is a «borderless» button. Borderless buttons resemble basic buttons except that they have no borders or background but still change appearance during different states, such as when clicked.
To create a borderless button, apply the borderlessButtonStyle style to the button. For example:
Custom background
If you want to truly redefine the appearance of your button, you can specify a custom background. Instead of supplying a simple bitmap or color, however, your background should be a state list resource that changes appearance depending on the button’s current state.
You can define the state list in an XML file that defines three different images or colors to use for the different button states.
To create a state list drawable for your button background:
- Create three bitmaps for the button background that represent the default, pressed, and focused button states.
To ensure that your images fit buttons of various sizes, create the bitmaps as Nine-patch bitmaps.
Источник