Поиск по сайту:

Android P: чипы и ChipGroup


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

Android-чипы

Фишки в основном представляют собой текст, отображаемый на закругленном фоне. Их можно проверить, и они также могут содержать значки. Чипы — это более новая и стилизованная форма RadioButtons. Чтобы использовать чипы в своем приложении для Android, вам необходимо использовать последнюю версию Android SDK 28. Ниже приведены зависимости, которые необходимо добавить в build.gradle:

implementation 'androidx.appcompat:appcompat:1.0.0-alpha1'
implementation 'com.google.android.material:material:1.0.0-alpha1'

Примечание. На момент написания выше были доступны версии. Что такое AndroidX? С момента появления Android Support v28 компания Google провела рефакторинг имен пакетов. AndroidX является заменой библиотеки поддержки. Для получения более подробной информации о новых именах пакетов перейдите по этой ссылке.

Использование чипа Android

Чип определяется в макете xml как:

<com.google.android.material.chip.Chip
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipText="Default" />

Типы чипсов

Чипсы могут быть оформлены как:

  • По умолчанию. При нажатии этой кнопки ничего не происходит, если не присутствует какой-либо другой атрибут xml.
  • Запись: нам нужно добавить style=@style/Widget.MaterialComponents.Chip.Entry. Это делает чип доступным для проверки и по умолчанию содержит галочку и значок закрытия.
  • Выбор: Этот тип чипа обычно используется для пометки/снятия маркера для выбора. style=@style/Widget.MaterialComponents.Chip.Choice Стиль выбора обычно используется в группах микросхем.
  • Действия. Этот чип можно проверить, и он используется для запуска действий при нажатии на них. style=@style/Widget.MaterialComponents.Chip.Action
  • Фильтр: эта микросхема может быть отмечена флажком и отмечена галочкой. style=@style/Widget.MaterialComponents.Chip.Filter

XML-атрибуты

  • приложение:chipText
  • приложение:chipBackgroundColor
  • app:rippleColor — для отображения пользовательского эффекта ряби при нажатии на чип.
  • app:checkable – используется для установки того, включен ли переключатель.
  • app:chipIcon – используется для установки пользовательского значка, который можно нарисовать в чипе.
  • app:closeIcon – обычно присутствует в чипе Entry. Мы можем установить нашу иконку, используя это. Значок закрытия по умолчанию находится справа от текста.
  • приложение:closeIconTint
  • app:checkedIcon — используется для изменения значка галочки, который присутствует в фишках типа Entry и Filter.
  • приложение:chipStartPadding/приложение:chipEndPadding
  • приложение:iconStartPadding/приложение:iconEndPadding

Давайте используем эти атрибуты в нашем XML-макете:

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <com.google.android.material.chip.Chip
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipText="Default" />

        <com.google.android.material.chip.Chip
            style="@style/Widget.MaterialComponents.Chip.Entry"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipText="Entry" />

        <com.google.android.material.chip.Chip
            style="@style/Widget.MaterialComponents.Chip.Choice"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipText="Choice" />

        <com.google.android.material.chip.Chip
            style="@style/Widget.MaterialComponents.Chip.Action"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipText="Action" />

        <com.google.android.material.chip.Chip
            style="@style/Widget.MaterialComponents.Chip.Filter"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipText="Filter" />


    </LinearLayout>
<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:orientation="horizontal">

        <com.google.android.material.chip.Chip
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipBackgroundColor="@android:color/holo_blue_bright"
            app:chipText="Background Color" />

        <com.google.android.material.chip.Chip
            style="@style/Widget.MaterialComponents.Chip.Choice"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipText="Ripple Color"
            app:rippleColor="@android:color/holo_orange_dark" />

        <com.google.android.material.chip.Chip
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipIcon="@mipmap/ic_launcher"
            app:chipText="Chip icon" />

    </LinearLayout>

Android ChipGroup

Подобно RadioGroups, ChipGroups используются для хранения чипов.

<com.google.android.material.chip.ChipGroup
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp">

        <com.google.android.material.chip.Chip
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipText="This" />

        <com.google.android.material.chip.Chip
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipText="is" />

        <com.google.android.material.chip.Chip
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipText="a" />

        <com.google.android.material.chip.Chip
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipText="because" />

        <com.google.android.material.chip.Chip
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipText="chip" />

        <com.google.android.material.chip.Chip
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipText="group" />


    </com.google.android.material.chip.ChipGroup>
<com.google.android.material.chip.ChipGroup
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        app:chipSpacing="25dp">

        <com.google.android.material.chip.Chip
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipText="Chip" />

        <com.google.android.material.chip.Chip
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipText="Group" />

        <com.google.android.material.chip.Chip
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipText="with" />

        <com.google.android.material.chip.Chip
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipText="custom" />

        <com.google.android.material.chip.Chip
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipText="spacing" />

    </com.google.android.material.chip.ChipGroup>

Чип Android, пример структуры проекта ChipGroup

Код чипов Android

Код макета activity_main.xml приведен ниже:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <com.google.android.material.chip.Chip
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipText="Default" />

        <com.google.android.material.chip.Chip
            style="@style/Widget.MaterialComponents.Chip.Entry"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipText="Entry" />

        <com.google.android.material.chip.Chip
            style="@style/Widget.MaterialComponents.Chip.Choice"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipText="Choice" />

        <com.google.android.material.chip.Chip
            style="@style/Widget.MaterialComponents.Chip.Action"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipText="Action" />

        <com.google.android.material.chip.Chip
            style="@style/Widget.MaterialComponents.Chip.Filter"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipText="Filter" />


    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:orientation="horizontal">

        <com.google.android.material.chip.Chip
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipBackgroundColor="@android:color/holo_blue_bright"
            app:chipText="Background Color" />

        <com.google.android.material.chip.Chip
            style="@style/Widget.MaterialComponents.Chip.Choice"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipText="Ripple Color"
            app:rippleColor="@android:color/holo_orange_dark" />

        <com.google.android.material.chip.Chip
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipIcon="@mipmap/ic_launcher"
            app:chipText="Chip icon" />

    </LinearLayout>

    <com.google.android.material.chip.ChipGroup
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp">

        <com.google.android.material.chip.Chip
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipText="This" />

        <com.google.android.material.chip.Chip
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipText="is" />

        <com.google.android.material.chip.Chip
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipText="a" />

        <com.google.android.material.chip.Chip
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipText="because" />

        <com.google.android.material.chip.Chip
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipText="chip" />

        <com.google.android.material.chip.Chip
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipText="group" />


    </com.google.android.material.chip.ChipGroup>

    <com.google.android.material.chip.ChipGroup
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        app:chipSpacing="25dp">

        <com.google.android.material.chip.Chip
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipText="Chip" />

        <com.google.android.material.chip.Chip
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipText="Group" />

        <com.google.android.material.chip.Chip
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipText="with" />

        <com.google.android.material.chip.Chip
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipText="custom" />

        <com.google.android.material.chip.Chip
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipText="spacing" />

    </com.google.android.material.chip.ChipGroup>


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:text="Choose One"
        android:textSize="18sp" />


    <com.google.android.material.chip.ChipGroup
        android:id="@+id/chipGroup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:singleSelection="true">

        <com.google.android.material.chip.Chip
            style="@style/Widget.MaterialComponents.Chip.Choice"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipText="Choice A" />

        <com.google.android.material.chip.Chip
            style="@style/Widget.MaterialComponents.Chip.Choice"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipText="Choice B" />

        <com.google.android.material.chip.Chip
            style="@style/Widget.MaterialComponents.Chip.Choice"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipText="Choice C" />

    </com.google.android.material.chip.ChipGroup>


    <HorizontalScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp">


        <com.google.android.material.chip.ChipGroup
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipSpacingHorizontal="25dp"
            app:singleLine="true">

            <com.google.android.material.chip.Chip
                style="@style/Widget.MaterialComponents.Chip.Choice"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:chipText="Chip" />

            <com.google.android.material.chip.Chip
                style="@style/Widget.MaterialComponents.Chip.Choice"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:chipText="Group" />


            <com.google.android.material.chip.Chip
                style="@style/Widget.MaterialComponents.Chip.Choice"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:chipText="in" />


            <com.google.android.material.chip.Chip
                style="@style/Widget.MaterialComponents.Chip.Choice"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:chipText="single" />

            <com.google.android.material.chip.Chip
                style="@style/Widget.MaterialComponents.Chip.Choice"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:chipText="line" />

            <com.google.android.material.chip.Chip
                style="@style/Widget.MaterialComponents.Chip.Choice"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:chipText="add" />

            <com.google.android.material.chip.Chip
                style="@style/Widget.MaterialComponents.Chip.Choice"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:chipText="a" />

            <com.google.android.material.chip.Chip
                style="@style/Widget.MaterialComponents.Chip.Choice"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:chipText="horizontal" />

            <com.google.android.material.chip.Chip
                style="@style/Widget.MaterialComponents.Chip.Choice"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:chipText="scroll" />

        </com.google.android.material.chip.ChipGroup>

    </HorizontalScrollView>


    <com.google.android.material.chip.Chip
        android:id="@+id/chip"
        style="@style/Widget.MaterialComponents.Chip.Entry"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="24dp"
        app:chipText="Close Icon Listener" />


</LinearLayout>

Мы заключили ChipGroup, состоящую только из одной строки, в представление с горизонтальной прокруткой. Код для класса MainActivity.java приведен ниже:

package com.journaldev.androidchipsandchipgroup;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.google.android.material.chip.Chip;
import com.google.android.material.chip.ChipGroup;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ChipGroup chipGroup = findViewById(R.id.chipGroup);

        chipGroup.setOnCheckedChangeListener(new ChipGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(ChipGroup chipGroup, int i) {

                Chip chip = chipGroup.findViewById(i);
                if (chip != null)
                    Toast.makeText(getApplicationContext(), "Chip is " + chip.getChipText(), Toast.LENGTH_SHORT).show();


            }
        });

        Chip chip = findViewById(R.id.chip);
        chip.setOnCloseIconClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getApplicationContext(), "Close is Clicked", Toast.LENGTH_SHORT).show();
            }
        });

    }
}

setOnCheckedChangeListener в ChipGroup срабатывает только в том случае, если ChipGroup настроен на один выбор.

AndroidChipsAndChipGroup

Ссылка на проект на гитхабе