How to make an Android Spinner with initial text Select One?
Here's a general solution that overrides the Spinner
view. It overrides setAdapter()
to set the initial position to -1, and proxies the supplied SpinnerAdapter
to display the prompt string for position less than 0.
This has been tested on Android 1.5 through 4.2, but buyer beware! Because this solution relies on reflection to call the private AdapterView.setNextSelectedPositionInt()
and AdapterView.setSelectedPositionInt()
, it's not guaranteed to work in future OS updates. It seems likely that it will, but it is by no means guaranteed.
Normally I wouldn't condone something like this, but this question has been asked enough times and it seems like a reasonable enough request that I thought I would post my solution.
/**
* A modified Spinner that doesn't automatically select the first entry in the list.
*
* Shows the prompt if nothing is selected.
*
* Limitations: does not display prompt if the entry list is empty.
*/
public class NoDefaultSpinner extends Spinner {
public NoDefaultSpinner(Context context) {
super(context);
}
public NoDefaultSpinner(Context context, AttributeSet attrs) {
super(context, attrs);
}
public NoDefaultSpinner(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void setAdapter(SpinnerAdapter orig ) {
final SpinnerAdapter adapter = newProxy(orig);
super.setAdapter(adapter);
try {
final Method m = AdapterView.class.getDeclaredMethod(
"setNextSelectedPositionInt",int.class);
m.setAccessible(true);
m.invoke(this,-1);
final Method n = AdapterView.class.getDeclaredMethod(
"setSelectedPositionInt",int.class);
n.setAccessible(true);
n.invoke(this,-1);
}
catch( Exception e ) {
throw new RuntimeException(e);
}
}
protected SpinnerAdapter newProxy(SpinnerAdapter obj) {
return (SpinnerAdapter) java.lang.reflect.Proxy.newProxyInstance(
obj.getClass().getClassLoader(),
new Class[]{SpinnerAdapter.class},
new SpinnerAdapterProxy(obj));
}
/**
* Intercepts getView() to display the prompt if position < 0
*/
protected class SpinnerAdapterProxy implements InvocationHandler {
protected SpinnerAdapter obj;
protected Method getView;
protected SpinnerAdapterProxy(SpinnerAdapter obj) {
this.obj = obj;
try {
this.getView = SpinnerAdapter.class.getMethod(
"getView",int.class,View.class,ViewGroup.class);
}
catch( Exception e ) {
throw new RuntimeException(e);
}
}
public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
try {
return m.equals(getView) &&
(Integer)(args[0])<0 ?
getView((Integer)args[0],(View)args[1],(ViewGroup)args[2]) :
m.invoke(obj, args);
}
catch (InvocationTargetException e) {
throw e.getTargetException();
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
protected View getView(int position, View convertView, ViewGroup parent)
throws IllegalAccessException {
if( position<0 ) {
final TextView v =
(TextView) ((LayoutInflater)getContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE)).inflate(
android.R.layout.simple_spinner_item,parent,false);
v.setText(getPrompt());
return v;
}
return obj.getView(position,convertView,parent);
}
}
}
How to set a default text to a Spinner
Use this code
declaration
String selected, spinner_item;
spinner code
sp.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
selected = sp.getSelectedItem().toString();
if (!selected.equals("Country"))
spinner_item = selected;
System.out.println(selected);
setid();
}
private void setid() {
sp.setSelection(sp_position);
t.setText(spinner_item);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
How to make an Android Spinner with initial text Select One?
Here's a general solution that overrides the Spinner
view. It overrides setAdapter()
to set the initial position to -1, and proxies the supplied SpinnerAdapter
to display the prompt string for position less than 0.
This has been tested on Android 1.5 through 4.2, but buyer beware! Because this solution relies on reflection to call the private AdapterView.setNextSelectedPositionInt()
and AdapterView.setSelectedPositionInt()
, it's not guaranteed to work in future OS updates. It seems likely that it will, but it is by no means guaranteed.
Normally I wouldn't condone something like this, but this question has been asked enough times and it seems like a reasonable enough request that I thought I would post my solution.
/**
* A modified Spinner that doesn't automatically select the first entry in the list.
*
* Shows the prompt if nothing is selected.
*
* Limitations: does not display prompt if the entry list is empty.
*/
public class NoDefaultSpinner extends Spinner {
public NoDefaultSpinner(Context context) {
super(context);
}
public NoDefaultSpinner(Context context, AttributeSet attrs) {
super(context, attrs);
}
public NoDefaultSpinner(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void setAdapter(SpinnerAdapter orig ) {
final SpinnerAdapter adapter = newProxy(orig);
super.setAdapter(adapter);
try {
final Method m = AdapterView.class.getDeclaredMethod(
"setNextSelectedPositionInt",int.class);
m.setAccessible(true);
m.invoke(this,-1);
final Method n = AdapterView.class.getDeclaredMethod(
"setSelectedPositionInt",int.class);
n.setAccessible(true);
n.invoke(this,-1);
}
catch( Exception e ) {
throw new RuntimeException(e);
}
}
protected SpinnerAdapter newProxy(SpinnerAdapter obj) {
return (SpinnerAdapter) java.lang.reflect.Proxy.newProxyInstance(
obj.getClass().getClassLoader(),
new Class[]{SpinnerAdapter.class},
new SpinnerAdapterProxy(obj));
}
/**
* Intercepts getView() to display the prompt if position < 0
*/
protected class SpinnerAdapterProxy implements InvocationHandler {
protected SpinnerAdapter obj;
protected Method getView;
protected SpinnerAdapterProxy(SpinnerAdapter obj) {
this.obj = obj;
try {
this.getView = SpinnerAdapter.class.getMethod(
"getView",int.class,View.class,ViewGroup.class);
}
catch( Exception e ) {
throw new RuntimeException(e);
}
}
public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
try {
return m.equals(getView) &&
(Integer)(args[0])<0 ?
getView((Integer)args[0],(View)args[1],(ViewGroup)args[2]) :
m.invoke(obj, args);
}
catch (InvocationTargetException e) {
throw e.getTargetException();
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
protected View getView(int position, View convertView, ViewGroup parent)
throws IllegalAccessException {
if( position<0 ) {
final TextView v =
(TextView) ((LayoutInflater)getContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE)).inflate(
android.R.layout.simple_spinner_item,parent,false);
v.setText(getPrompt());
return v;
}
return obj.getView(position,convertView,parent);
}
}
}
How to set default Text in Android Spinner
first of all you should declare
ArrayList<TableData> tableDatas = new ArrayList<TableData>();
outside forloop
as you are adding all the entries in that list
add your default value first inside list
then write forloop
for adding all the values in json array
and then use spinner.setSelection(0);
method to show defult value in spinner as you have added it in 1st position in an array
following is code
ArrayList<TableData> tableDatas = new ArrayList<TableData>();
//for default value
TableData tables = new TableData();
tables.setTblId(0);
tables.setTblName("Select");
tableDatas.add(tables);
JSONArray tablearray = tablenamejson.getJSONArray("data");
for (int i = 0; i < tablearray.length(); i++) {
JSONObject jsonObject = tablearray.getJSONObject(i);
String table_id = jsonObject.getString(TAG_TABLE_ID);
String table_name = jsonObject.getString(TAG_TABLE_NAME);
TableData tables = new TableData();
tables.setTblId(table_id);
tables.setTblName(table_name);
tableDatas.add(tables);
}
adapter = new TableAdapter(tableDatas, getActivity());
spinner.setAdapter(adapter);
spinner.setSelection(0);
setting initial text on spinner
Put "Select" at 0 position in your list or array which you are using to create Spinner.
Setting of spinner default text?
Add element at 0th index using .add(0,"Select Item");
MORE CLEAR
arraylist.add(0,"Select Item"); //Add element at 0th index
ArrayAdapter<String> adp=new ArrayAdapter<String> (this,android.R.layout.simple_spinner_dropdown_item,arraylist);
spinner.setAdapter(adp);
Set text of spinner before item is selected
You can do that one of two ways.
1) Add "Select One" as the first item in your xml and code your listener to ignore that as a selection.
2) Create a custom adapter to insert it as the first line,
EDIT
In your resources
<string-array name="listarray">
<item>Select One</item>
<item>Item One</item>
<item>Item Two</item>
<item>Item Three</item>
</string-array>
In your onItemSelected Listener:
spinnername.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (pos == 0) {
}else {
// Your code to process the selection
}
}
});
Related Topics
Save Arraylist to Sharedpreferences
Android Listview With Different Layouts For Each Row
How to Show Current Location on a Google Map on Android Marshmallow
Changing Locale Within the App Itself
This App Won't Run Unless You Update Google Play Services (Via Bazaar)
Drawing a Line/Path on Google Maps
How to Capture the "Virtual Keyboard Show/Hide" Event in Android
Detect Home Button Press in Android
How to Create an Object of an Activity in Other Class
Key Hash For Android-Facebook App
How to Run a Runnable Thread in Android At Defined Intervals