How to create Hint Spinner

Spinners provide a quick way to select one value from a set. In the default state, a spinner shows its currently selected value. Touching the spinner displays a dropdown menu with all other available values, from which the user can select a new one. For example,

Spin Spinner is view that displays one child at a time and lets the user pick among them. The items in the Spinner come from the "Adapter" associated with this view. By default Spinner comes with selection of first item added on the Adapter. However there are the situation when we want to add some "hint" to a Spinner such as "Please select a value from spinner", but unfortunately there's no hint method for adapter/spinner available. Hence if we want to do so we have to extend the "Adapter" class and override the getCount() method. Here's an example :

HintAdapter.java


import android.content.Context;

import android.widget.ArrayAdapter;

public class HintAdapter extends ArrayAdapter<String> {


public HintAdapter(Context context, int textViewResourceId) {

super(context, textViewResourceId);
// TODO Auto-generated constructor stub
}

@Override

public int getCount() {
// TODO Auto-generated method stub
int count = super.getCount();
return count>0 ? count-1 : count ;
}


}

Now, whenever we want to use our custom "HintAdapter" we can simple instantiate the HintAdapter class as,


HintAdapter adapter = new HintAdapter(Activity_1_2.this, android.R.layout.simple_list_item_1);
adapter.addAll(object_of_items_to_be_added);
adapter.add("Here's our hint");
sp.setAdapter(adapter);
sp.setSelection(adapter.getCount());

Above mention code will show us a spinner with selection "Here's our hint." When we will open the dropdown menu this option will not be there in the available items.

Output of above code would be like this :



No comments:

Post a Comment