Android Spinner 禁用選項 (Disable item)

找了很久都找不到要怎麼禁用Spinner裡面的item,

只好自己寫一個Adapter,獻醜了。

SpinnerArrayAdapter.java
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

import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class SpinnerArrayAdapter extends ArrayAdapter<String>{

private int[] ItemPositionIsDisable;

public SpinnerArrayAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}

public SpinnerArrayAdapter(Context context, int textViewResourceId, String[] objects) {
super(context, textViewResourceId,objects);
ItemPositionIsDisable = new int[objects.length];
}

public SpinnerArrayAdapter(Context context,String[] objects){
this(context, android.R.layout.simple_spinner_item,objects);
this.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}

public SpinnerArrayAdapter(int stringArrayResourceId,Context context){
this(context, context.getResources().getStringArray(stringArrayResourceId));
}

public boolean isEnabled(int position) {
if (ItemPositionIsDisable[position]==1)
return false;
return true;
}

public void setItemPositionIsDisable(int position,boolean IsDisable) {

ItemPositionIsDisable[position] = (IsDisable) ? 1 : 0;
}

@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {

View mView = super.getDropDownView(position, convertView, parent);
TextView mTextView = (TextView) mView;

if (ItemPositionIsDisable[position] == 1) {

mTextView.setTextColor(Color.GRAY);

} else if (ItemPositionIsDisable[position] == 0) {
mTextView.setTextColor(Color.BLACK);
}
return mView;

}
}

用法也很簡單,

使用setItemPositionIsDisable(int position,boolean IsDisable)來設定就好,

並且支持直接使用R.array中的Resource,以下是用法範例。

1
2
3
4
5
SpinnerArrayAdapter mSpinnerArrayAdapter = new SpinnerArrayAdapter(R.array.level_array,this);
mSpinnerArrayAdapter.setItemPositionIsDisable(1,true);
mSpinnerArrayAdapter.setItemPositionIsDisable(2,true);
mSpinnerArrayAdapter.setItemPositionIsDisable(3,true);
mSpinner.setAdapter(mSpinnerArrayAdapter);

提供大家參考!