因为系统提供的Spinner不能够满足业务需求:
1.默认展示hint
2.点击时若无数据则提示用户
3.有数据时点击展示列表,用户不选择时不赋值,用户选择赋值并触发选择事件
4.可以动态设置数据,设置数据后自动展开列表,不做默认选择
5.重新初始化spinner,展示hint,清空数据
于是根据上述需求根据TextView+Popwindow自定义了一个仿系统spinner,支持xml配置数据和提示,二话不说先看效果图:
根据需求,先画出自定义spinner的流程图:
步骤1:新建BasePopWindow,继承PopupWindow,除自动设置可点击以及电机外部消失外,设置外部半透明的背景,并在show和dismiss的时候自动展示及隐藏(此处引用他人代码)
public class BasePopWindow extends PopupWindow {
//ValueAnimator会从1平滑过渡到0的值的效果
private ValueAnimator valueAnimator = ValueAnimator.ofFloat(1f, 0f).setDuration(500);
public BasePopWindow(View contentView, int width, int height, boolean focusable) {
super(contentView, width, height, focusable);
setBackgroundDrawable(new ColorDrawable(-0x90000000));//设置背景半透明
update();//刷新update()在以下状态下要更新 ,This include: setClippingEnabled(boolean), setFocusable(boolean), setIgnoreCheekPress(),setInputMethodMode(int), setTouchable(boolean), and setAnimationStyle(int).
setTouchable(true);// 设置PopupWindow可触摸
setOutsideTouchable(true);// 设置允许在外点击消失
contentView.setFocusableInTouchMode(true);//调用View的setFocusableInTouchMode(true)可以使View在Touch Mode模式之下仍然可获得焦点
}
@Override
public void showAtLocation(View parent, int gravity, int x, int y) {
super.showAtLocation(parent, gravity, x, y);
showTransBackground(true);
}
@Override
public void showAsDropDown(View anchor) {
super.showAsDropDown(anchor);
showTransBackground(true);
}
@Override
public void dismiss() {
super.dismiss();
showTransBackground(false);
}
public void showTransBackground(final boolean isTrans) {
final Window window = ((Activity) getContentView().getContext()).getWindow();
if (window == null) {
return;
}
valueAnimator.removeAllListeners();
valueAnimator.removeAllUpdateListeners();
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float fraction = (float) animation.getAnimatedValue();
WindowManager.LayoutParams lp = window.getAttributes();
if (isTrans) {
lp.alpha = 0.7f + 0.3f * fraction;//从不透明平滑过渡到0.7
} else {
lp.alpha = 0.7f + (1 - fraction) * 0.3f;//从0.7平滑过渡到不透明
}
window.setAttributes(lp);
}
});
valueAnimator.start();
}
}