Android 中自定义控件实现 AppCompatSpinner 功能
在为实现沉浸式效果需要隐藏导航栏的应用中,由于采用系统自带的 AppCompatSpinner 控件实现下拉列表选择功能时,底部会出现一个白色导航栏,目前未找到隐藏的办法,故只能完全自定义一个下拉列表选择控件。
1、基本思路
- 定义一个内容项的布局,包含一个 TextView 和一个 ImageView 。
- 定义一个包含 RecyclerView 控件的 PopupWindow 下拉窗口。
- 定义 RecyclerView 的 子项布局和 Adapter 适配器。
- 定义下拉列表打开和关闭时的动画效果。
- 自定义一个下拉列表控件。
2、内容项布局文件
- custom_spinner_item.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"><TextViewandroid:id="@+id/item_text"android:layout_width="match_parent"android:layout_height="match_parent"android:textSize="@dimen/sp_20"android:textColor="@color/white"android:paddingHorizontal="@dimen/dp_20"android:gravity="center_vertical"app:layout_constraintLeft_toLeftOf="parent"app:layout_constraintTop_toTopOf="parent"app:layout_constraintBottom_toBottomOf="parent"/><ImageViewandroid:layout_width="wrap_content"android:layout_height="match_parent"android:src="@mipmap/weather_sun"app:layout_constraintTop_toTopOf="parent"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintRight_toRightOf="parent"android:layout_marginEnd="@dimen/dp_20"tools:ignore="ContentDescription" /></androidx.constraintlayout.widget.ConstraintLayout>
3、下拉列表布局文件
- custom_spinner_dropdown.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:background="@color/white"xmlns:app="http://schemas.android.com/apk/res-auto"><androidx.recyclerview.widget.RecyclerViewandroid:id="@+id/dropdown_recycler"android:layout_width="match_parent"android:layout_height="@dimen/dp_200"android:scrollbars="vertical"android:fadeScrollbars="false"app:layout_constraintLeft_toLeftOf="parent"app:layout_constraintTop_toTopOf="parent"/></androidx.constraintlayout.widget.ConstraintLayout>
4、下拉列表子项布局文件
- custom_spinner_dropdown_item.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="wrap_content"xmlns:app="http://schemas.android.com/apk/res-auto"><TextViewandroid:id="@+id/text_view"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textColor="@color/text_black"android:textSize="@dimen/sp_20"android:paddingHorizontal="@dimen/dp_10"android