How to disable an item in a Spinner
Is it possible to display particular entries in a Spinner list as disabled?
I.e., I want to always display a spinner with four entries (North, South, East, and West, say), but I want to be able to disable any one of these so that is appears greyed out and not selectable.
Is this possible, or will I have to recreate the list each time, leaving开发者_Python百科 out the invalid entries?
// Create spinner month, and disable month < today
List<CharSequence> listMonth = new ArrayList<CharSequence>();
for (int m = 0; m < 12; m++) {
if (m < 9) {
listMonth.add("0" + (m + 1));
} else {
listMonth.add("" + (m + 1));
}
}
// Create spinner item
adapterMonth = new ArrayAdapter<CharSequence>(this,
R.layout.layout_spinner_item, listMonth) {
// Disable click item < month current
@Override
public boolean isEnabled(int position) {
// TODO Auto-generated method stub
if (year <= max_year && position < max_month - 1) {
return false;
}
return true;
}
// Change color item
@Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
View mView = super.getDropDownView(position, convertView, parent);
TextView mTextView = (TextView) mView;
if (year <= max_year && position < max_month - 1) {
mTextView.setTextColor(Color.GRAY);
} else {
mTextView.setTextColor(Color.BLACK);
}
return mView;
}
};
adapterMonth
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn2.setAdapter(adapterMonth);
public class MySpinnerAdapter extends BaseAdapter {
@Override
public void isEnabled(int position) {
return getItem(position).isEnabled();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
convertView = View.inflate(parent.getContext(), R.layout.item, null);
}
if(!isEnabled(position)) {
convertView.setEnabled(false);
convertView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//NO-OP: Just intercept click on disabled item
}
});
}
return convertView;
}
}
Someone just posted a solution to your problem, refer to this old post.
Is this possible
It doesn't appear so. The way you would do that with ListView
involves areAllItemsEnabled()
and isEnabled()
. However, those are methods on the ListAdapter
interface, not the SpinnerAdapter
interface. So, I suspect they will be ignored by a Spinner
.
class SpinnerAdapter(context: Context, resource: Int, list: ArrayList<String>)
: ArrayAdapter<String>(context, resource, list) {
override fun isEnabled(position: Int): Boolean {
// select position to disable
return position != 0
}
}
精彩评论