Wednesday, April 23, 2014

Android Spinner with initial text “Select One”

first you should create custom ArrayAdapter with a String for your desired text in its constructor. Then, you should switch the first element of your array with your default text, and after the user click on the spinner it should switch back to the original array.

public class DefaultActivity extends Activity {

    Spinner spinner;
    String defaultTextForSpinner = "text here";
    String[] arrayForSpinner = {"One", "Two", "Three"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_spinner);

        spinner = (Spinner) findViewById(R.id.spinner_district);
        spinner.setAdapter(new CustomSpinnerAdapter(this, R.layout.spinner_row, arrayForSpinner, defaultTextForSpinner));
    }
    }

  public class CustomSpinnerAdapter extends ArrayAdapter<String>{

    Context context;
    String[] objects;
    String firstElement;
    boolean isFirstTime;

    public CustomSpinnerAdapter(Context context, int textViewResourceId, String[] objects, String defaultText) {
        super(context, textViewResourceId, objects);
        this.context = context;
        this.objects = objects;
        this.isFirstTime = true;
        setDefaultText(defaultText);
    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        if(isFirstTime) {
            objects[0] = firstElement;
            isFirstTime = false;
        }
        return getCustomView(position, convertView, parent);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) { 
        notifyDataSetChanged();
        return getCustomView(position, convertView, parent);
    }

    public void setDefaultText(String defaultText) {
        this.firstElement = objects[0];
        objects[0] = defaultText;
    }

    public View getCustomView(int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View row = inflater.inflate(R.layout.tremps_spinner_row, parent, false);
        TextView label = (TextView) row.findViewById(R.id.tremps_spinner_text);
        label.setText(objects[position]);

        return row;
    }

    }