Toolbar. Menu – Devcolibri – Android для начинающих

Toolbar. Menu

Структура урока:

Стилизация элемента Toolbar

В этом уроке нам необходимо сделать тулбар такого вида:

Наша цель

Добавление Toolbar-компонента

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

Сперва, как и в предыдущем уроке про тулбар, добавим элемент Toolbar в layout файл Activity:

custom_toolbar_activity_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        style="@style/Toolbar"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/toolbar"/>


</android.support.constraint.ConstraintLayout>

А теперь внутрь элемента Toolbar мы добавим необходимые элементы для функциональности поиска: EditText и Button. Toolbar является ViewGroup, поэтому в него можно помещать элементы, как и в любой другой контейнер. Единственный нюанс — Toolbar располагает элементы один над одним по умолчанию (как FrameLayout).

custom_toolbar_activity_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        style="@style/Toolbar"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">


        <RelativeLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:padding="8dp">


            <EditText
                android:id="@+id/search_edit_text"
                android:layout_width="match_parent"
                android:layout_marginEnd="20dp"
                android:layout_toStartOf="@+id/search_button"
                android:layout_height="wrap_content"
                android:hint="Введите имя"/>


            <Button
                android:id="@+id/search_button"
                android:layout_alignParentEnd="true"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Поиск"/>


        </RelativeLayout>


    </android.support.v7.widget.Toolbar>


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/toolbar"/>


</android.support.constraint.ConstraintLayout>

Запустим приложение:

Первый результат

Видим, что всё отобразилось, но визуально выглядит не очень.

Стилизация Toolbar-компонента

Нам надо поменять стили у наших элементов EditText и Button.

Давайте усовершенствуем наш EditText:

custom_toolbar_activity_layout.xml

<EditText
    android:id="@+id/query_edit_text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_marginEnd="10dp"
    android:layout_toStartOf="@+id/search_button"
    android:background="@null"
    android:maxLines="1"
    android:imeOptions="actionSearch"
    android:inputType="text"
    android:hint="@string/search_hint"/>

Объясним новые атрибуты:

  • android:maxLines="1" — означает, что EditText не будет поддерживать многострочный режим и весь текст будет располагаться в одну строку.
  • android:imeOptions="actionSearch" и android:inputType="text" добавляют в клавиатуру пользователя кнопку поиска, нажатие по которой в дальнейшем мы сможем обработать.
  • android:background="@null" убирает нижнюю линию, которая по умолчанию присутствует в EditText.

Также некоторые изменения претерпела кнопка поиска. Вот как выглядит наша кнопка со всеми атрибутами:

custom_toolbar_activity_layout.xml

<Button
    android:id="@+id/search_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:minWidth="0dp"
    android:minHeight="0dp"
    android:layout_alignParentEnd="true"
    android:backgroundTint="@android:color/white"
    android:background="@drawable/ic_search_black_24dp"/>

В качестве android:background мы использовали сгенерированную векторную иконку search.

Также мы установили атрибутам значение minWidth, minHeight 0dp, т.к. по умолчанию кнопки в Android системе имеют минимальную ширину и высоту. В данном случае нам это мешает, поэтому мы переопределяем эти значения.

Обработка событий Toolbar-компонента

Теперь мы можем работать с элементами тулбара как и с любыми другими элементами экрана. Давайте добавим Toolbar и его вложенные элементы в Activity.

CustomToolbarActivity.java

public class CustomToolbarActivity extends AppCompatActivity {
    
    private Toolbar toolbar;
    private EditText queryEditText;
    private Button searchButton;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.custom_toolbar_activity_layout);


        toolbar = findViewById(R.id.toolbar);
        queryEditText = toolbar.findViewById(R.id.query_edit_text);
        searchButton = toolbar.findViewById(R.id.search_button);
    }
}

Ничего необычного. Только вложенные элементы мы ищем используя toolbar.findViewById(). Это сделано для оптимизации поиска элементов. Поиск будет проходить только внутри Toolbar элемента, а не во всех элементах CustomToolbarActivity.

Теперь давайте добавим слушателей на нажатие кнопки поиска и на нажатие кнопки search внутри клавиатуры:

CustomToolbarActivity.java

public class CustomToolbarActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {


        // остальной код выше не изменился


        searchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(v.getContext(), R.string.search_hint, Toast.LENGTH_SHORT).show();
            }
        });


        queryEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    Toast.makeText(v.getContext(), R.string.search_hint, Toast.LENGTH_SHORT).show();
                    return true;
                }
                return false;
            }
        });
    }
}

Если вы сейчас запустите приложение, то увидите, что стало гораздо лучше:

Результат.

В результате данного урока мы:

  • отработали навыки работы с Toolbar;
  • узнали, каким образом наполнить Toolbar пользовательскими элементами.
УВИДЕТЬ ВСЕ Добавить заметку
Вы
Добавить ваш комментарий
 

Сайт использует cookie-файлы для того, чтобы вам было удобнее им пользоваться. Для продолжения работы с сайтом, вам необходимо принять использование cookie-файлов.

Я ознакомлен(а)