Android Spinner 禁用選項 (Disable item)

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

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

SpinnerArrayAdapter.java
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,以下是用法範例。

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

提供大家參考!

Comments

comments powered by Disqus