Android实现Spinner重复监听

首先重构Spinner类

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
60
61
62
63
import android.content.Context;
import android.util.AttributeSet;
import android.widget.Spinner;

/*
重构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();
}
}

然后将布局文件的标签修改为重构的View类

1
2
<!-- 这里使用了自定义控件的全路径名称 --><com.example.common.util.ReSpinner
.../>
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2022-2024 Konsin
  • 访问人数: | 浏览次数:

请我喝杯咖啡吧~

支付宝
微信