Chip – уникальный виджет из библиотеки Material Design, который чаще всего используют для отображения опций, которые мы выбрали.
Давайте создадим три кнопки с названиями городов, по которым мы будем тапать. При каждом тапе у нас будут создаваться чипы с названиями тех городов по кнопкам которых мы тапнули.
Для начала нам нужно в xml шаблоне нашего Activity разместить три кнопки
<?xml version="1.0" encoding="utf-8"?>
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimaryDark"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:id="@+id/butRostov"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
app:layout_constraintTop_toTopOf="parent"
android:text="@string/rostov"
app:icon="@drawable/location"
android:background="@color/colorPrimary"
style="@style/Widget.MaterialComponents.Button.Icon"/>
<Button
android:id="@+id/butLos"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
app:layout_constraintTop_toBottomOf="@id/butRostov"
android:text="@string/los"
app:icon="@drawable/location"
android:background="@color/colorPrimary"
style="@style/Widget.MaterialComponents.Button.Icon"/>
<Button
android:id="@+id/butYork"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
app:layout_constraintTop_toBottomOf="@id/butLos"
android:text="@string/york"
app:icon="@drawable/location"
android:background="@color/colorPrimary"
style="@style/Widget.MaterialComponents.Button.Icon"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
После этого под кнопками нужно также разместить виджет, в котором мы будем создавать чипы. Этот виджет называется ChipGroup
Но мы будем не просто создавать, а еще и размещать в горизонтальную линию с функционалом прокрутки – поэтому наш виджет ChipGroup мы разместим внутри HorizontalScrollView.
В общем наш код в xml шаблоне будет вот такой
<?xml version="1.0" encoding="utf-8"?>
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimaryDark"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:id="@+id/butRostov"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
app:layout_constraintTop_toTopOf="parent"
android:text="@string/rostov"
app:icon="@drawable/location"
android:background="@color/colorPrimary"
style="@style/Widget.MaterialComponents.Button.Icon"/>
<Button
android:id="@+id/butLos"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
app:layout_constraintTop_toBottomOf="@id/butRostov"
android:text="@string/los"
app:icon="@drawable/location"
android:background="@color/colorPrimary"
style="@style/Widget.MaterialComponents.Button.Icon"/>
<Button
android:id="@+id/butYork"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
app:layout_constraintTop_toBottomOf="@id/butLos"
android:text="@string/york"
app:icon="@drawable/location"
android:background="@color/colorPrimary"
style="@style/Widget.MaterialComponents.Button.Icon"/>
<HorizontalScrollView
android:id="@+id/sectGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="@id/butYork">
<com.google.android.material.chip.ChipGroup
android:id="@+id/group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
app:singleLine="true"/>
</HorizontalScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
Для того что бы наши чипы могли горизонтально прокручиваться, то есть скролиться – мы для СhipGroup устанавливаем вот этот атрибут:
app:singleLine="true"
Теперь нам нужно создать макет наших чипов. Для этого в папке layout мы создаём xml шаблон, в котором разместим виджет Chip. Я назову этот файл chip_item.xml.
Я размещу там вот такой xml код:
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.chip.Chip
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/chipItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_margin="10dp"
app:chipIcon="@drawable/location"
app:chipIconTint="@color/colorPrimaryDark"
app:closeIcon="@drawable/close"
app:closeIconTint="@color/colorPrimaryDark"
style="@style/Widget.MaterialComponents.Chip.Entry"/>
Давайте по подробнее пройдемся по самым важным атрибутам
app:chipIcon=”@drawable/location” – устанавливаем иконку нашего чипа (слева)
app:chipIconTint=”@color/colorPrimaryDark” – устанавливаем цвет иконки нашего чипа (слева)
app:closeIcon=”@drawable/close” – устанавливаем иконку для удаления нашего чипа (справа)
app:closeIconTint=”@color/colorPrimaryDark” – устанавливаем цвет иконки для удаления нашего чипа (справа)
style=”@style/Widget.MaterialComponents.Chip.Entry” – устанавливаем стиль для отображения наших чипов. Без этого чипы не будут работать
Далее мы переходим в класс нашего Activity.
Во-первых мы вешаем обработку тапов по нашим кнопкам
binding?.butRostov?.setOnClickListener(this)
binding?.butLos?.setOnClickListener(this)
binding?.butYork?.setOnClickListener(this)
Относим наш класс к интерфейсу для реализации методов тапов
class MainActivity : AppCompatActivity(),View.OnClickListener
Далее мы реализуем метод обработки тапов по кнопкам
override fun onClick(view: View) {
val inflater = LayoutInflater.from(this@MainActivity)
val chip = inflater.inflate(R.layout.chip_item, null, false) as Chip
binding?.group?.setOnCheckedChangeListener { group, checkedId ->
chip.let { binding?.youSelected?.text = chip?.text }
}
chip.setOnCloseIconClickListener { v -> binding?.group?.removeView(v) }
when(view.id) {
R.id.butRostov -> {
chip.text = binding?.butRostov?.text
binding?.group?.addView(chip)
}
R.id.butLos -> {
chip.text = binding?.butLos?.text
binding?.group?.addView(chip)
}
R.id.butYork -> {
chip.text = binding?.butYork?.text
binding?.group?.addView(chip)
}
}
}
Во-первых мы должны создать объект наших чипов по макету chip_item.xml
val inflater = LayoutInflater.from(this@MainActivity)
val chip = inflater.inflate(R.layout.chip_item, null, false) as Chip
Далее в методах обработки тапов мы должны записать в название чипа, то есть в текстовое поле – текст из соответствующего текстового поля кнопки, по которой тапнули. То есть в название чипа мы передаём название кнопки. Также мы вызываем функцию addView () для создания чипа в ChipGroup . Например при тапе по кнопке с id – butRostov мы размещаем вот такой код
chip.text = binding?.butRostov?.text
binding?.group?.addView(chip)
Во-вторых нам нужно реализовать метод удаления чипа из ChipGroup при тапе по соответствующей иконке чипа:
chip.setOnCloseIconClickListener { v -> binding?.group?.removeView(v) }
Теперь наши чипы начнут функционировать
Код из урока
activity_main.xml – xml шаблон Activity
<?xml version="1.0" encoding="utf-8"?>
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimaryDark"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:id="@+id/butRostov"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
app:layout_constraintTop_toTopOf="parent"
android:text="@string/rostov"
app:icon="@drawable/location"
android:background="@color/colorPrimary"
style="@style/Widget.MaterialComponents.Button.Icon"/>
<Button
android:id="@+id/butLos"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
app:layout_constraintTop_toBottomOf="@id/butRostov"
android:text="@string/los"
app:icon="@drawable/location"
android:background="@color/colorPrimary"
style="@style/Widget.MaterialComponents.Button.Icon"/>
<Button
android:id="@+id/butYork"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
app:layout_constraintTop_toBottomOf="@id/butLos"
android:text="@string/york"
app:icon="@drawable/location"
android:background="@color/colorPrimary"
style="@style/Widget.MaterialComponents.Button.Icon"/>
<HorizontalScrollView
android:id="@+id/sectGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="@id/butYork">
<com.google.android.material.chip.ChipGroup
android:id="@+id/group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
app:singleLine="true"/>
</HorizontalScrollView>
<androidx.appcompat.widget.AppCompatTextView
android:id="@+id/youSelected"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@id/sectGroup"
android:layout_margin="10dp"
android:textColor="@android:color/white"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
chip_item.xml – xml шаблон наших чипов
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.chip.Chip
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/chipItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_margin="10dp"
app:chipIcon="@drawable/location"
app:chipIconTint="@color/colorPrimaryDark"
app:closeIcon="@drawable/close"
app:closeIconTint="@color/colorPrimaryDark"
style="@style/Widget.MaterialComponents.Chip.Entry"/>
MainActivity.kt – класс Activity
class MainActivity : AppCompatActivity(),View.OnClickListener {
var binding:ActivityMainBinding? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
binding?.butRostov?.setOnClickListener(this)
binding?.butLos?.setOnClickListener(this)
binding?.butYork?.setOnClickListener(this)
}
override fun onClick(view: View) {
val inflater = LayoutInflater.from(this@MainActivity)
val chip = inflater.inflate(R.layout.chip_item, null, false) as Chip
chip.setOnCloseIconClickListener { v -> binding?.group?.removeView(v) }
when(view.id) {
R.id.butRostov -> {
chip.text = binding?.butRostov?.text
binding?.group?.addView(chip)
}
R.id.butLos -> {
chip.text = binding?.butLos?.text
binding?.group?.addView(chip)
}
R.id.butYork -> {
chip.text = binding?.butYork?.text
binding?.group?.addView(chip)
}
}
}
}
ДОМАШНЕЕ ЗАДАНИЕ
Создайте кнопки, при тапе по которым должны создаваться чипы. Результат в формате видео пришлите на Whats App – +79612777611