代码:
Spinner spinner = findViewById(R.id.spinner); // 获取下拉控件
spinner.setDropDownVerticalOffset(62); // 下拉的纵向偏移
String[] spinnerItems = {"请选择楼号", "1号楼", "2号楼", "3号楼"}; // 数据
// 自定义选中的界面样式(上下文,样式,文本框资源Id,数组)
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(this, R.layout.item_select, R.id.text, spinnerItems);
// 自定义下拉的界面样式
spinnerAdapter.setDropDownViewResource(R.layout.item_drop);
// 设置适配器
spinner.setAdapter(spinnerAdapter);
// 设置Item选择监听器
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.i(TAG, "onItemClick: spinnerItem");
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
Log.i(TAG, "onNothingSelected: spinnerItem");
}
});
布局:activity_main.xml
<Spinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:popupBackground="@android:color/transparent"
android:background="@android:color/transparent" />
布局:item_select.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#151836">
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/bg_btn"
android:gravity="center"
android:text="请选择楼号"
android:textColor="#FEFEFE"
android:textSize="20sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/bg_btn"
android:drawableEnd="@drawable/arrow"
android:paddingEnd="20dp" />
</FrameLayout>
布局:item_drop.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#151836">
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/bg_btn"
android:gravity="center"
android:text="请选择楼号"
android:textColor="#FEFEFE"
android:textSize="20sp" />
</FrameLayout>
参考链接: