Android Spinner重复选择某一项获取回调事件的方法

问题

使用Android SDK自带的Spinner控件时,如果当前已经选中了一项,再次点开Spinner的下拉菜单并选中相同一项时,不会触发OnItemSelectedListener
的onItemSelected()回调方法,因此无法获知用户再次选中了相同项.一般情况下,如果用户选中相同项,我们确实不需要做任何操作,因此也就不关心该项是否再次
被用户选择.但是有些时候,仍需要获取这样的监听.比如一个Spinner的菜单是本日,本周,本月,自定义时,当用户选中自定义时间段后,想再次改变
自定义的时间段,此时Spinner并不能触发再次点击自定义项的回调.问题由此而来.

解决办法

网上有很多相关解决办法,还有说不用Spinner转而用PopupWindow+ListView手动实现一个的.目前看来一下方法最简单:

使用自定义的ReSpinner,继承自Spinner.当相同项被选中时,手动触发OnItemSelectedListener的onItemSelected()方法.代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import android.content.Context;
import android.util.AttributeSet;
import android.widget.Spinner;

public class ReSpinner extends Spinner {
public boolean isDropDownMenuShown=false;//标志下拉列表是否正在显示

public ReSpinner(Context context) {
super(context);
}

public ReSpinner(Context context, AttributeSet attrs) {
super(context, attrs);
}

public ReSpinner(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}

@Override
public void
setSelection(int position, boolean animate) {
boolean sameSelected = position == getSelectedItemPosition();
super.setSelection(position, animate);
if (sameSelected) {
// 如果选择项是Spinner当前已选择的项,则 OnItemSelectedListener并不会触发,因此这里手动触发回调
getOnItemSelectedListener().onItemSelected(this, getSelectedView(), position, getSelectedItemId());
}
}

@Override
public boolean performClick() {
this.isDropDownMenuShown = true;
return super.performClick();
}

public boolean isDropDownMenuShown(){
return isDropDownMenuShown;
}

public void setDropDownMenuShown(boolean isDropDownMenuShown){
this.isDropDownMenuShown=isDropDownMenuShown;
}

@Override
public void
setSelection(int position) {
boolean sameSelected = position == getSelectedItemPosition();
super.setSelection(position);
if (sameSelected) {
getOnItemSelectedListener().onItemSelected(this, getSelectedView(), position, getSelectedItemId());
}
}

@Override
public void onDetachedFromWindow() {
super.onDetachedFromWindow();
}
}

相关参考

How can I get an event in Android Spinner when the current selected item is selected again?