How to set Spinner default value to null?
I'm trying to get a Spinner to load up with no selected value. Once the user selects a value it then takes them to another page.
This is proving to be a problem because at present, the page just loads straight away before the user gets a choice to choose.
My spinner class is set up the same way as Google's: http://developer.android.com/resources/tutorials/views/hello-spinner.html
So basically, is it possible have a spinner that loads with nothing selected because at present, it loads the first item in my string array.
android android-spinner
add a comment |
I'm trying to get a Spinner to load up with no selected value. Once the user selects a value it then takes them to another page.
This is proving to be a problem because at present, the page just loads straight away before the user gets a choice to choose.
My spinner class is set up the same way as Google's: http://developer.android.com/resources/tutorials/views/hello-spinner.html
So basically, is it possible have a spinner that loads with nothing selected because at present, it loads the first item in my string array.
android android-spinner
Check for stackoverflow.com/questions/867518/… Especially answer 40. Work like magic!
– iftach barshem
Jan 16 '14 at 14:13
I posted a really nice solution to this here: stackoverflow.com/a/39923282/681122
– Steven L
Oct 7 '16 at 18:01
Check out aaronvargas answer here: stackoverflow.com/questions/867518/…
– live-love
Mar 9 '18 at 18:30
add a comment |
I'm trying to get a Spinner to load up with no selected value. Once the user selects a value it then takes them to another page.
This is proving to be a problem because at present, the page just loads straight away before the user gets a choice to choose.
My spinner class is set up the same way as Google's: http://developer.android.com/resources/tutorials/views/hello-spinner.html
So basically, is it possible have a spinner that loads with nothing selected because at present, it loads the first item in my string array.
android android-spinner
I'm trying to get a Spinner to load up with no selected value. Once the user selects a value it then takes them to another page.
This is proving to be a problem because at present, the page just loads straight away before the user gets a choice to choose.
My spinner class is set up the same way as Google's: http://developer.android.com/resources/tutorials/views/hello-spinner.html
So basically, is it possible have a spinner that loads with nothing selected because at present, it loads the first item in my string array.
android android-spinner
android android-spinner
edited Jan 13 '17 at 15:03
Jonik
52.1k55210317
52.1k55210317
asked Jan 18 '11 at 16:34
OliOli
4092615
4092615
Check for stackoverflow.com/questions/867518/… Especially answer 40. Work like magic!
– iftach barshem
Jan 16 '14 at 14:13
I posted a really nice solution to this here: stackoverflow.com/a/39923282/681122
– Steven L
Oct 7 '16 at 18:01
Check out aaronvargas answer here: stackoverflow.com/questions/867518/…
– live-love
Mar 9 '18 at 18:30
add a comment |
Check for stackoverflow.com/questions/867518/… Especially answer 40. Work like magic!
– iftach barshem
Jan 16 '14 at 14:13
I posted a really nice solution to this here: stackoverflow.com/a/39923282/681122
– Steven L
Oct 7 '16 at 18:01
Check out aaronvargas answer here: stackoverflow.com/questions/867518/…
– live-love
Mar 9 '18 at 18:30
Check for stackoverflow.com/questions/867518/… Especially answer 40. Work like magic!
– iftach barshem
Jan 16 '14 at 14:13
Check for stackoverflow.com/questions/867518/… Especially answer 40. Work like magic!
– iftach barshem
Jan 16 '14 at 14:13
I posted a really nice solution to this here: stackoverflow.com/a/39923282/681122
– Steven L
Oct 7 '16 at 18:01
I posted a really nice solution to this here: stackoverflow.com/a/39923282/681122
– Steven L
Oct 7 '16 at 18:01
Check out aaronvargas answer here: stackoverflow.com/questions/867518/…
– live-love
Mar 9 '18 at 18:30
Check out aaronvargas answer here: stackoverflow.com/questions/867518/…
– live-love
Mar 9 '18 at 18:30
add a comment |
10 Answers
10
active
oldest
votes
is it possible have a spinner that loads with nothing selected
Only if there is no data. If you have 1+ items in the SpinnerAdapter
, the Spinner
will always have a selection.
Spinners
are not designed to be command widgets. Users will not expect a selection in a Spinner
to start an activity. Please consider using something else, like a ListView
or GridView
, instead of a Spinner
.
EDIT
BTW, I forgot to mention -- you can always put an extra entry in your adapter that represents "no selection", and make it the initial selected item in the Spinner
.
Ok thanks.Ive just gone for a simple button at present with an alertbox to choose which screen they go to. Its only a prototype atm. thanks for your help
– Oli
Jan 18 '11 at 16:58
8
What about displaying the items? I don't want the "dummy one" to be selected.
– Krzysztof Wolny
Nov 27 '11 at 14:22
+1 for Spinners are not designed to be command widgets
– Mohammad Ersan
Jan 27 '14 at 22:30
2
ListPopupWindow is better option in this case. By replacing spinner from textView and calling ListPopupWindow.show() on textView click shows the same behaviour with no drawback of default item selection. For more detail see this developer.android.com/reference/android/widget/…
– brijesh kumar
Jan 10 '17 at 19:09
This answer doesn't help as others do. It shouldn't be accepted.
– CoolMind
Nov 20 '18 at 7:35
add a comment |
Alternatively, you could override your spinner adapter, and provide an empty view for position 0 in your getView method, and a view with 0dp height in the getDropDownView
method.
This way, you have an initial text such as "Select an Option..." that shows up when the spinner is first loaded, but it is not an option for the user to choose (technically it is, but because the height is 0, they can't see it).
That's definitely the best working solution.
– lukas
Nov 17 '13 at 22:00
1
Has anyone actually tried this? Seems like it is not as straightforward as it sounds.
– Matthias
Jan 14 '14 at 17:40
1
I found a working example: stackoverflow.com/q/9863378/1084488
– Matthias
Jan 14 '14 at 18:02
I posted one full implementation of this idea in a new answer. You need to take a couple of things into account, such as overridinggetCount()
, but it's doable.
– Jonik
Jan 13 '17 at 15:07
add a comment |
This is a complete implementation of Paul Bourdeaux's idea, namely returning a special initial view (or an empty view) in getView()
for position 0.
It works for me and is relatively straightforward. You might consider this approach especially if you already have a custom adapter for your Spinner. (In my case, I was using custom adapter in order to easily customise the layout of the items, each item having a couple of TextViews.)
The adapter would be something along these lines:
public class MySpinnerAdapter extends ArrayAdapter<MyModel> {
public MySpinnerAdapter(Context context, List<MyModel> items) {
super(context, R.layout.my_spinner_row, items);
}
@Override
public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent) {
if (position == 0) {
return initialSelection(true);
}
return getCustomView(position, convertView, parent);
}
@NonNull
@Override
public View getView(int position, View convertView, @NonNull ViewGroup parent) {
if (position == 0) {
return initialSelection(false);
}
return getCustomView(position, convertView, parent);
}
@Override
public int getCount() {
return super.getCount() + 1; // Adjust for initial selection item
}
private View initialSelection(boolean dropdown) {
// Just an example using a simple TextView. Create whatever default view
// to suit your needs, inflating a separate layout if it's cleaner.
TextView view = new TextView(getContext());
view.setText(R.string.select_one);
int spacing = getContext().getResources().getDimensionPixelSize(R.dimen.spacing_smaller);
view.setPadding(0, spacing, 0, spacing);
if (dropdown) { // Hidden when the dropdown is opened
view.setHeight(0);
}
return view;
}
private View getCustomView(int position, View convertView, ViewGroup parent) {
// Distinguish "real" spinner items (that can be reused) from initial selection item
View row = convertView != null && !(convertView instanceof TextView)
? convertView :
LayoutInflater.from(getContext()).inflate(R.layout.my_spinner_row, parent, false);
position = position - 1; // Adjust for initial selection item
MyModel item = getItem(position);
// ... Resolve views & populate with data ...
return row;
}
}
That's it. Note that if you use a OnItemSelectedListener
with your Spinner, in onItemSelected()
you'd also have to adjust position
to take the default item into account, for example:
if (position == 0) {
return;
} else {
position = position - 1;
}
MyModel selected = items.get(position);
1
I like this idea, don't know why it had only one vote.
– Omaraf
Mar 23 '17 at 3:07
I haven't got it working yet...I'm just a newbie...I don't have "R.layout.my_spinner_row". Where do I get this from or what do I put instead?
– Tim Cooper
Feb 10 '18 at 6:17
add a comment |
In my case, although size '2' is displayed in the spinner, nothing happens till some selection is done!
I have an xml file (data_sizes.xml) which lists all the spinner values.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="chunks">
<item>2</item>
<item>4</item>
<item>8</item>
<item>16</item>
<item>32</item>
</string-array>
</resources>
In main.xml file: Spinner element
<Spinner android:id="@+id/spinnerSize"
android:layout_marginLeft="50px"
android:layout_width="fill_parent"
android:drawSelectorOnTop="true"
android:layout_marginTop="5dip"
android:prompt="@string/SelectSize"
android:layout_marginRight="30px"
android:layout_height="35px" />
Then in my java code, I added:
In my activity: Declaration
Spinner spinnerSize;
ArrayAdapter adapter;
In a public void function - initControls(): Definition
spinnerSize = (Spinner)findViewById(R.id.spinnerSize);
adapter = ArrayAdapter.createFromResource(this, R.array.chunks, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSize.setAdapter(adapter);
spinnerSize.setOnItemSelectedListener(new MyOnItemSelectedListener());
My spinner listener:
/* Spinner Listener */
class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
chunkSize = new Integer(parent.getItemAtPosition(pos).toString()).intValue();
}
public void onNothingSelected(AdapterView<?> parent) {
// Dummy
}
}
add a comment |
Using a custom spinner layout like this:
<?xml version="1.0" encoding="utf-8"?>
<Spinner xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/spinnerTarget"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="14dp"
android:textColor="#000000"/>
In the activity:
// populate the list
ArrayList<String> dataList = new ArrayList<String>();
for (int i = 0; i < 4; i++) {
dataList.add("Item");
}
// set custom layout spinner_layout.xml and adapter
Spinner spinnerObject = (Spinner) findViewById(R.id.spinnerObject);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, R.drawable.spinner_layout, dataList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerObject.setAdapter(dataAdapter);
spinnerObject.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// to set value of first selection, because setOnItemSelectedListener will not dispatch if the user selects first element
TextView spinnerTarget = (TextView)v.findViewById(R.id.spinnerTarget);
spinnerTarget.setText(spinnerObject.getSelectedItem().toString());
return false;
}
});
spinnerObject.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
private boolean selectionControl = true;
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
// just the first time
if(selectionControl){
// find TextView in layout
TextView spinnerTarget = (TextView)parent.findViewById(R.id.spinnerTarget);
// set spinner text empty
spinnerTarget.setText("");
selectionControl = false;
}
else{
// select object
}
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
add a comment |
Merge this:
private long previousItemId = 0;
@Override
public long getItemId(int position) {
long nextItemId = random.nextInt(Integer.MAX_VALUE);
while(previousItemId == nextItemId) {
nextItemId = random.nextInt(Integer.MAX_VALUE);
}
previousItemId = nextItemId;
return nextItemId;
}
With this answer:
public class SpinnerInteractionListener
implements AdapterView.OnItemSelectedListener, View.OnTouchListener {
private AdapterView.OnItemSelectedListener onItemSelectedListener;
public SpinnerInteractionListener(AdapterView.OnItemSelectedListener selectedListener) {
this.onItemSelectedListener = selectedListener;
}
boolean userSelect = false;
@Override
public boolean onTouch(View v, MotionEvent event) {
userSelect = true;
return false;
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if(userSelect) {
onItemSelectedListener.onItemSelected(parent, view, pos, id);
userSelect = false;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
if(userSelect) {
onItemSelectedListener.onNothingSelected(parent);
userSelect = false;
}
}
}
add a comment |
you can put the first cell in your array to be empty({"","some","some",...})
and do nothing if the position is 0;
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(position>0) {
label.setText(MainActivity.questions[position - 1]);
}
}
- if you fill the array by xml file you can let the first item empty
add a comment |
My solution, in case you have a TextView as each row of the spinner:
// TODO: add a fake item as the last one of "items"
final ArrayAdapter<String> adapter=new ArrayAdapter<String>(..,..,items)
{
@Override
public View getDropDownView(final int position,final View convertView,final ViewGroup parent)
{
final View dropDownView=super.getDropDownView(position,convertView,parent);
((TextView)dropDownView.findViewById(android.R.id.text1)).setHeight(position==getCount()-1?0:getDimensionFromAttribute(..,R.attr.dropdownListPreferredItemHeight));
dropDownView.getLayoutParams().height=position==getCount()-1?0:LayoutParams.MATCH_PARENT;
return dropDownView;
}
}
...
spinner.setAdapter(adapter);
_actionModeSpinnerView.setSelection(dataAdapter.getCount()-1,false);
public static int getDimensionFromAttribute(final Context context,final int attr)
{
final TypedValue typedValue=new TypedValue();
if(context.getTheme().resolveAttribute(attr,typedValue,true))
return TypedValue.complexToDimensionPixelSize(typedValue.data,context.getResources().getDisplayMetrics());
return 0;
}
add a comment |
Base on @Jonik answer I have created fully functional extension to ArrayAdapter
class SpinnerArrayAdapter<T> : ArrayAdapter<T> {
private val selectText : String
private val resource: Int
private val fieldId : Int
private val inflater : LayoutInflater
constructor(context: Context?, resource: Int, objects: Array<T>, selectText : String? = null) : super(context, resource, objects) {
this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
this.resource = resource
this.fieldId = 0
this.inflater = LayoutInflater.from(context)
}
constructor(context: Context?, resource : Int, objects: List<T>, selectText : String? = null) : super(context, resource, objects) {
this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
this.resource = resource
this.fieldId = 0
this.inflater = LayoutInflater.from(context)
}
constructor(context: Context?, resource: Int, textViewResourceId: Int, objects: Array<T>, selectText : String? = null) : super(context, resource, textViewResourceId, objects) {
this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
this.resource = resource
this.fieldId = textViewResourceId
this.inflater = LayoutInflater.from(context)
}
constructor(context: Context?, resource : Int, textViewResourceId: Int, objects: List<T>, selectText : String? = null) : super(context, resource, textViewResourceId, objects) {
this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
this.resource = resource
this.fieldId = textViewResourceId
this.inflater = LayoutInflater.from(context)
}
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup?): View {
if(position == 0) {
return initialSelection(true)
}
return createViewFromResource(inflater, position -1, convertView, parent, resource)
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
if(position == 0) {
return initialSelection(false)
}
return createViewFromResource(inflater, position -1, convertView, parent, resource)
}
override fun getCount(): Int {
return super.getCount() + 1 // adjust for initial selection
}
private fun initialSelection(inDropDown: Boolean) : View {
// Just simple TextView as initial selection.
val view = TextView(context)
view.setText(selectText)
view.setPadding(8, 0, 8, 0)
if(inDropDown) {
// Hide when dropdown is open
view.height = 0
}
return view
}
private fun createViewFromResource(inflater: LayoutInflater, position: Int,
@Nullable convertView: View?, parent: ViewGroup?, resource: Int): View {
val view: View
val text: TextView?
if (convertView == null || (convertView is TextView)) {
view = inflater.inflate(resource, parent, false)
} else {
view = convertView
}
try {
if (fieldId === 0) {
// If no custom field is assigned, assume the whole resource is a TextView
text = view as TextView
} else {
// Otherwise, find the TextView field within the layout
text = view.findViewById(fieldId)
if (text == null) {
throw RuntimeException("Failed to find view with ID "
+ context.getResources().getResourceName(fieldId)
+ " in item layout")
}
}
} catch (e: ClassCastException) {
Log.e("ArrayAdapter", "You must supply a resource ID for a TextView")
throw IllegalStateException(
"ArrayAdapter requires the resource ID to be a TextView", e)
}
val item = getItem(position)
if (item is CharSequence) {
text.text = item
} else {
text.text = item!!.toString()
}
return view
}
add a comment |
I assume that you want to have a Spinner
with first empty invisible item (that is a strange feature of Spinner
that cannot show a list without selecting an item). You should add a class that will contain data:
data class YourData(val id: Int, val name: String?)
This is the adapter.
class YourAdapter(
context: Context,
private val textViewResourceId: Int,
private var items: ArrayList<YourData>
) : ArrayAdapter<YourData>(context, textViewResourceId, items) {
private var inflater: LayoutInflater = context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
override fun getCount(): Int = items.size + 1
override fun getItem(position: Int): YourData? =
if (position == 0) YourData(0, "") else items[position - 1]
override fun getItemId(position: Int): Long = position.toLong()
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View =
if (position == 0) {
getFirstTextView(convertView)
} else {
getTextView(convertView, parent, position - 1)
}
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View =
getView(position, convertView, parent)
private fun getFirstTextView(convertView: View?): View {
// Just simple TextView as initial selection.
var textView: TextView? = convertView as? TextView
val holder: FirstViewHolder
if (textView?.tag !is FirstViewHolder) {
textView = TextView(context) // inflater.inflate(R.layout.your_text, parent, false) as TextView
textView.height = 0 // Hide first item.
holder = FirstViewHolder()
holder.textView = textView
textView.tag = holder
}
return textView
}
private fun getTextView(
convertView: View?,
parent: ViewGroup,
position: Int
): TextView {
var textView: TextView? = convertView as? TextView
val holder: ViewHolder
if (textView?.tag is ViewHolder) {
holder = textView.tag as ViewHolder
} else {
textView = inflater.inflate(textViewResourceId, parent, false) as TextView
holder = ViewHolder()
holder.textView = textView
textView.tag = holder
}
holder.textView.text = items[position].name
return textView
}
private class FirstViewHolder {
lateinit var textView: TextView
}
private class ViewHolder {
lateinit var textView: TextView
}
}
To create:
YourAdapter(context!!, R.layout.text_item, ArrayList())
To add items:
private fun fill(items: List<YourData>, adapter: YourAdapter) {
adapter.run {
clear()
addAll(items)
notifyDataSetChanged()
}
}
When you load items to your Spinner
with that fill()
command, you should know, that indices are also incremented. So if you wish to select 3rd item, you should now select 4th: spinner?.setSelection(index + 1)
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4726490%2fhow-to-set-spinner-default-value-to-null%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
10 Answers
10
active
oldest
votes
10 Answers
10
active
oldest
votes
active
oldest
votes
active
oldest
votes
is it possible have a spinner that loads with nothing selected
Only if there is no data. If you have 1+ items in the SpinnerAdapter
, the Spinner
will always have a selection.
Spinners
are not designed to be command widgets. Users will not expect a selection in a Spinner
to start an activity. Please consider using something else, like a ListView
or GridView
, instead of a Spinner
.
EDIT
BTW, I forgot to mention -- you can always put an extra entry in your adapter that represents "no selection", and make it the initial selected item in the Spinner
.
Ok thanks.Ive just gone for a simple button at present with an alertbox to choose which screen they go to. Its only a prototype atm. thanks for your help
– Oli
Jan 18 '11 at 16:58
8
What about displaying the items? I don't want the "dummy one" to be selected.
– Krzysztof Wolny
Nov 27 '11 at 14:22
+1 for Spinners are not designed to be command widgets
– Mohammad Ersan
Jan 27 '14 at 22:30
2
ListPopupWindow is better option in this case. By replacing spinner from textView and calling ListPopupWindow.show() on textView click shows the same behaviour with no drawback of default item selection. For more detail see this developer.android.com/reference/android/widget/…
– brijesh kumar
Jan 10 '17 at 19:09
This answer doesn't help as others do. It shouldn't be accepted.
– CoolMind
Nov 20 '18 at 7:35
add a comment |
is it possible have a spinner that loads with nothing selected
Only if there is no data. If you have 1+ items in the SpinnerAdapter
, the Spinner
will always have a selection.
Spinners
are not designed to be command widgets. Users will not expect a selection in a Spinner
to start an activity. Please consider using something else, like a ListView
or GridView
, instead of a Spinner
.
EDIT
BTW, I forgot to mention -- you can always put an extra entry in your adapter that represents "no selection", and make it the initial selected item in the Spinner
.
Ok thanks.Ive just gone for a simple button at present with an alertbox to choose which screen they go to. Its only a prototype atm. thanks for your help
– Oli
Jan 18 '11 at 16:58
8
What about displaying the items? I don't want the "dummy one" to be selected.
– Krzysztof Wolny
Nov 27 '11 at 14:22
+1 for Spinners are not designed to be command widgets
– Mohammad Ersan
Jan 27 '14 at 22:30
2
ListPopupWindow is better option in this case. By replacing spinner from textView and calling ListPopupWindow.show() on textView click shows the same behaviour with no drawback of default item selection. For more detail see this developer.android.com/reference/android/widget/…
– brijesh kumar
Jan 10 '17 at 19:09
This answer doesn't help as others do. It shouldn't be accepted.
– CoolMind
Nov 20 '18 at 7:35
add a comment |
is it possible have a spinner that loads with nothing selected
Only if there is no data. If you have 1+ items in the SpinnerAdapter
, the Spinner
will always have a selection.
Spinners
are not designed to be command widgets. Users will not expect a selection in a Spinner
to start an activity. Please consider using something else, like a ListView
or GridView
, instead of a Spinner
.
EDIT
BTW, I forgot to mention -- you can always put an extra entry in your adapter that represents "no selection", and make it the initial selected item in the Spinner
.
is it possible have a spinner that loads with nothing selected
Only if there is no data. If you have 1+ items in the SpinnerAdapter
, the Spinner
will always have a selection.
Spinners
are not designed to be command widgets. Users will not expect a selection in a Spinner
to start an activity. Please consider using something else, like a ListView
or GridView
, instead of a Spinner
.
EDIT
BTW, I forgot to mention -- you can always put an extra entry in your adapter that represents "no selection", and make it the initial selected item in the Spinner
.
edited Jan 18 '11 at 16:57
answered Jan 18 '11 at 16:47
CommonsWareCommonsWare
773k13918891936
773k13918891936
Ok thanks.Ive just gone for a simple button at present with an alertbox to choose which screen they go to. Its only a prototype atm. thanks for your help
– Oli
Jan 18 '11 at 16:58
8
What about displaying the items? I don't want the "dummy one" to be selected.
– Krzysztof Wolny
Nov 27 '11 at 14:22
+1 for Spinners are not designed to be command widgets
– Mohammad Ersan
Jan 27 '14 at 22:30
2
ListPopupWindow is better option in this case. By replacing spinner from textView and calling ListPopupWindow.show() on textView click shows the same behaviour with no drawback of default item selection. For more detail see this developer.android.com/reference/android/widget/…
– brijesh kumar
Jan 10 '17 at 19:09
This answer doesn't help as others do. It shouldn't be accepted.
– CoolMind
Nov 20 '18 at 7:35
add a comment |
Ok thanks.Ive just gone for a simple button at present with an alertbox to choose which screen they go to. Its only a prototype atm. thanks for your help
– Oli
Jan 18 '11 at 16:58
8
What about displaying the items? I don't want the "dummy one" to be selected.
– Krzysztof Wolny
Nov 27 '11 at 14:22
+1 for Spinners are not designed to be command widgets
– Mohammad Ersan
Jan 27 '14 at 22:30
2
ListPopupWindow is better option in this case. By replacing spinner from textView and calling ListPopupWindow.show() on textView click shows the same behaviour with no drawback of default item selection. For more detail see this developer.android.com/reference/android/widget/…
– brijesh kumar
Jan 10 '17 at 19:09
This answer doesn't help as others do. It shouldn't be accepted.
– CoolMind
Nov 20 '18 at 7:35
Ok thanks.Ive just gone for a simple button at present with an alertbox to choose which screen they go to. Its only a prototype atm. thanks for your help
– Oli
Jan 18 '11 at 16:58
Ok thanks.Ive just gone for a simple button at present with an alertbox to choose which screen they go to. Its only a prototype atm. thanks for your help
– Oli
Jan 18 '11 at 16:58
8
8
What about displaying the items? I don't want the "dummy one" to be selected.
– Krzysztof Wolny
Nov 27 '11 at 14:22
What about displaying the items? I don't want the "dummy one" to be selected.
– Krzysztof Wolny
Nov 27 '11 at 14:22
+1 for Spinners are not designed to be command widgets
– Mohammad Ersan
Jan 27 '14 at 22:30
+1 for Spinners are not designed to be command widgets
– Mohammad Ersan
Jan 27 '14 at 22:30
2
2
ListPopupWindow is better option in this case. By replacing spinner from textView and calling ListPopupWindow.show() on textView click shows the same behaviour with no drawback of default item selection. For more detail see this developer.android.com/reference/android/widget/…
– brijesh kumar
Jan 10 '17 at 19:09
ListPopupWindow is better option in this case. By replacing spinner from textView and calling ListPopupWindow.show() on textView click shows the same behaviour with no drawback of default item selection. For more detail see this developer.android.com/reference/android/widget/…
– brijesh kumar
Jan 10 '17 at 19:09
This answer doesn't help as others do. It shouldn't be accepted.
– CoolMind
Nov 20 '18 at 7:35
This answer doesn't help as others do. It shouldn't be accepted.
– CoolMind
Nov 20 '18 at 7:35
add a comment |
Alternatively, you could override your spinner adapter, and provide an empty view for position 0 in your getView method, and a view with 0dp height in the getDropDownView
method.
This way, you have an initial text such as "Select an Option..." that shows up when the spinner is first loaded, but it is not an option for the user to choose (technically it is, but because the height is 0, they can't see it).
That's definitely the best working solution.
– lukas
Nov 17 '13 at 22:00
1
Has anyone actually tried this? Seems like it is not as straightforward as it sounds.
– Matthias
Jan 14 '14 at 17:40
1
I found a working example: stackoverflow.com/q/9863378/1084488
– Matthias
Jan 14 '14 at 18:02
I posted one full implementation of this idea in a new answer. You need to take a couple of things into account, such as overridinggetCount()
, but it's doable.
– Jonik
Jan 13 '17 at 15:07
add a comment |
Alternatively, you could override your spinner adapter, and provide an empty view for position 0 in your getView method, and a view with 0dp height in the getDropDownView
method.
This way, you have an initial text such as "Select an Option..." that shows up when the spinner is first loaded, but it is not an option for the user to choose (technically it is, but because the height is 0, they can't see it).
That's definitely the best working solution.
– lukas
Nov 17 '13 at 22:00
1
Has anyone actually tried this? Seems like it is not as straightforward as it sounds.
– Matthias
Jan 14 '14 at 17:40
1
I found a working example: stackoverflow.com/q/9863378/1084488
– Matthias
Jan 14 '14 at 18:02
I posted one full implementation of this idea in a new answer. You need to take a couple of things into account, such as overridinggetCount()
, but it's doable.
– Jonik
Jan 13 '17 at 15:07
add a comment |
Alternatively, you could override your spinner adapter, and provide an empty view for position 0 in your getView method, and a view with 0dp height in the getDropDownView
method.
This way, you have an initial text such as "Select an Option..." that shows up when the spinner is first loaded, but it is not an option for the user to choose (technically it is, but because the height is 0, they can't see it).
Alternatively, you could override your spinner adapter, and provide an empty view for position 0 in your getView method, and a view with 0dp height in the getDropDownView
method.
This way, you have an initial text such as "Select an Option..." that shows up when the spinner is first loaded, but it is not an option for the user to choose (technically it is, but because the height is 0, they can't see it).
edited Apr 5 '12 at 13:50
Andro Selva
42.5k43175224
42.5k43175224
answered Feb 14 '12 at 23:22
Paul BourdeauxPaul Bourdeaux
27132
27132
That's definitely the best working solution.
– lukas
Nov 17 '13 at 22:00
1
Has anyone actually tried this? Seems like it is not as straightforward as it sounds.
– Matthias
Jan 14 '14 at 17:40
1
I found a working example: stackoverflow.com/q/9863378/1084488
– Matthias
Jan 14 '14 at 18:02
I posted one full implementation of this idea in a new answer. You need to take a couple of things into account, such as overridinggetCount()
, but it's doable.
– Jonik
Jan 13 '17 at 15:07
add a comment |
That's definitely the best working solution.
– lukas
Nov 17 '13 at 22:00
1
Has anyone actually tried this? Seems like it is not as straightforward as it sounds.
– Matthias
Jan 14 '14 at 17:40
1
I found a working example: stackoverflow.com/q/9863378/1084488
– Matthias
Jan 14 '14 at 18:02
I posted one full implementation of this idea in a new answer. You need to take a couple of things into account, such as overridinggetCount()
, but it's doable.
– Jonik
Jan 13 '17 at 15:07
That's definitely the best working solution.
– lukas
Nov 17 '13 at 22:00
That's definitely the best working solution.
– lukas
Nov 17 '13 at 22:00
1
1
Has anyone actually tried this? Seems like it is not as straightforward as it sounds.
– Matthias
Jan 14 '14 at 17:40
Has anyone actually tried this? Seems like it is not as straightforward as it sounds.
– Matthias
Jan 14 '14 at 17:40
1
1
I found a working example: stackoverflow.com/q/9863378/1084488
– Matthias
Jan 14 '14 at 18:02
I found a working example: stackoverflow.com/q/9863378/1084488
– Matthias
Jan 14 '14 at 18:02
I posted one full implementation of this idea in a new answer. You need to take a couple of things into account, such as overriding
getCount()
, but it's doable.– Jonik
Jan 13 '17 at 15:07
I posted one full implementation of this idea in a new answer. You need to take a couple of things into account, such as overriding
getCount()
, but it's doable.– Jonik
Jan 13 '17 at 15:07
add a comment |
This is a complete implementation of Paul Bourdeaux's idea, namely returning a special initial view (or an empty view) in getView()
for position 0.
It works for me and is relatively straightforward. You might consider this approach especially if you already have a custom adapter for your Spinner. (In my case, I was using custom adapter in order to easily customise the layout of the items, each item having a couple of TextViews.)
The adapter would be something along these lines:
public class MySpinnerAdapter extends ArrayAdapter<MyModel> {
public MySpinnerAdapter(Context context, List<MyModel> items) {
super(context, R.layout.my_spinner_row, items);
}
@Override
public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent) {
if (position == 0) {
return initialSelection(true);
}
return getCustomView(position, convertView, parent);
}
@NonNull
@Override
public View getView(int position, View convertView, @NonNull ViewGroup parent) {
if (position == 0) {
return initialSelection(false);
}
return getCustomView(position, convertView, parent);
}
@Override
public int getCount() {
return super.getCount() + 1; // Adjust for initial selection item
}
private View initialSelection(boolean dropdown) {
// Just an example using a simple TextView. Create whatever default view
// to suit your needs, inflating a separate layout if it's cleaner.
TextView view = new TextView(getContext());
view.setText(R.string.select_one);
int spacing = getContext().getResources().getDimensionPixelSize(R.dimen.spacing_smaller);
view.setPadding(0, spacing, 0, spacing);
if (dropdown) { // Hidden when the dropdown is opened
view.setHeight(0);
}
return view;
}
private View getCustomView(int position, View convertView, ViewGroup parent) {
// Distinguish "real" spinner items (that can be reused) from initial selection item
View row = convertView != null && !(convertView instanceof TextView)
? convertView :
LayoutInflater.from(getContext()).inflate(R.layout.my_spinner_row, parent, false);
position = position - 1; // Adjust for initial selection item
MyModel item = getItem(position);
// ... Resolve views & populate with data ...
return row;
}
}
That's it. Note that if you use a OnItemSelectedListener
with your Spinner, in onItemSelected()
you'd also have to adjust position
to take the default item into account, for example:
if (position == 0) {
return;
} else {
position = position - 1;
}
MyModel selected = items.get(position);
1
I like this idea, don't know why it had only one vote.
– Omaraf
Mar 23 '17 at 3:07
I haven't got it working yet...I'm just a newbie...I don't have "R.layout.my_spinner_row". Where do I get this from or what do I put instead?
– Tim Cooper
Feb 10 '18 at 6:17
add a comment |
This is a complete implementation of Paul Bourdeaux's idea, namely returning a special initial view (or an empty view) in getView()
for position 0.
It works for me and is relatively straightforward. You might consider this approach especially if you already have a custom adapter for your Spinner. (In my case, I was using custom adapter in order to easily customise the layout of the items, each item having a couple of TextViews.)
The adapter would be something along these lines:
public class MySpinnerAdapter extends ArrayAdapter<MyModel> {
public MySpinnerAdapter(Context context, List<MyModel> items) {
super(context, R.layout.my_spinner_row, items);
}
@Override
public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent) {
if (position == 0) {
return initialSelection(true);
}
return getCustomView(position, convertView, parent);
}
@NonNull
@Override
public View getView(int position, View convertView, @NonNull ViewGroup parent) {
if (position == 0) {
return initialSelection(false);
}
return getCustomView(position, convertView, parent);
}
@Override
public int getCount() {
return super.getCount() + 1; // Adjust for initial selection item
}
private View initialSelection(boolean dropdown) {
// Just an example using a simple TextView. Create whatever default view
// to suit your needs, inflating a separate layout if it's cleaner.
TextView view = new TextView(getContext());
view.setText(R.string.select_one);
int spacing = getContext().getResources().getDimensionPixelSize(R.dimen.spacing_smaller);
view.setPadding(0, spacing, 0, spacing);
if (dropdown) { // Hidden when the dropdown is opened
view.setHeight(0);
}
return view;
}
private View getCustomView(int position, View convertView, ViewGroup parent) {
// Distinguish "real" spinner items (that can be reused) from initial selection item
View row = convertView != null && !(convertView instanceof TextView)
? convertView :
LayoutInflater.from(getContext()).inflate(R.layout.my_spinner_row, parent, false);
position = position - 1; // Adjust for initial selection item
MyModel item = getItem(position);
// ... Resolve views & populate with data ...
return row;
}
}
That's it. Note that if you use a OnItemSelectedListener
with your Spinner, in onItemSelected()
you'd also have to adjust position
to take the default item into account, for example:
if (position == 0) {
return;
} else {
position = position - 1;
}
MyModel selected = items.get(position);
1
I like this idea, don't know why it had only one vote.
– Omaraf
Mar 23 '17 at 3:07
I haven't got it working yet...I'm just a newbie...I don't have "R.layout.my_spinner_row". Where do I get this from or what do I put instead?
– Tim Cooper
Feb 10 '18 at 6:17
add a comment |
This is a complete implementation of Paul Bourdeaux's idea, namely returning a special initial view (or an empty view) in getView()
for position 0.
It works for me and is relatively straightforward. You might consider this approach especially if you already have a custom adapter for your Spinner. (In my case, I was using custom adapter in order to easily customise the layout of the items, each item having a couple of TextViews.)
The adapter would be something along these lines:
public class MySpinnerAdapter extends ArrayAdapter<MyModel> {
public MySpinnerAdapter(Context context, List<MyModel> items) {
super(context, R.layout.my_spinner_row, items);
}
@Override
public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent) {
if (position == 0) {
return initialSelection(true);
}
return getCustomView(position, convertView, parent);
}
@NonNull
@Override
public View getView(int position, View convertView, @NonNull ViewGroup parent) {
if (position == 0) {
return initialSelection(false);
}
return getCustomView(position, convertView, parent);
}
@Override
public int getCount() {
return super.getCount() + 1; // Adjust for initial selection item
}
private View initialSelection(boolean dropdown) {
// Just an example using a simple TextView. Create whatever default view
// to suit your needs, inflating a separate layout if it's cleaner.
TextView view = new TextView(getContext());
view.setText(R.string.select_one);
int spacing = getContext().getResources().getDimensionPixelSize(R.dimen.spacing_smaller);
view.setPadding(0, spacing, 0, spacing);
if (dropdown) { // Hidden when the dropdown is opened
view.setHeight(0);
}
return view;
}
private View getCustomView(int position, View convertView, ViewGroup parent) {
// Distinguish "real" spinner items (that can be reused) from initial selection item
View row = convertView != null && !(convertView instanceof TextView)
? convertView :
LayoutInflater.from(getContext()).inflate(R.layout.my_spinner_row, parent, false);
position = position - 1; // Adjust for initial selection item
MyModel item = getItem(position);
// ... Resolve views & populate with data ...
return row;
}
}
That's it. Note that if you use a OnItemSelectedListener
with your Spinner, in onItemSelected()
you'd also have to adjust position
to take the default item into account, for example:
if (position == 0) {
return;
} else {
position = position - 1;
}
MyModel selected = items.get(position);
This is a complete implementation of Paul Bourdeaux's idea, namely returning a special initial view (or an empty view) in getView()
for position 0.
It works for me and is relatively straightforward. You might consider this approach especially if you already have a custom adapter for your Spinner. (In my case, I was using custom adapter in order to easily customise the layout of the items, each item having a couple of TextViews.)
The adapter would be something along these lines:
public class MySpinnerAdapter extends ArrayAdapter<MyModel> {
public MySpinnerAdapter(Context context, List<MyModel> items) {
super(context, R.layout.my_spinner_row, items);
}
@Override
public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent) {
if (position == 0) {
return initialSelection(true);
}
return getCustomView(position, convertView, parent);
}
@NonNull
@Override
public View getView(int position, View convertView, @NonNull ViewGroup parent) {
if (position == 0) {
return initialSelection(false);
}
return getCustomView(position, convertView, parent);
}
@Override
public int getCount() {
return super.getCount() + 1; // Adjust for initial selection item
}
private View initialSelection(boolean dropdown) {
// Just an example using a simple TextView. Create whatever default view
// to suit your needs, inflating a separate layout if it's cleaner.
TextView view = new TextView(getContext());
view.setText(R.string.select_one);
int spacing = getContext().getResources().getDimensionPixelSize(R.dimen.spacing_smaller);
view.setPadding(0, spacing, 0, spacing);
if (dropdown) { // Hidden when the dropdown is opened
view.setHeight(0);
}
return view;
}
private View getCustomView(int position, View convertView, ViewGroup parent) {
// Distinguish "real" spinner items (that can be reused) from initial selection item
View row = convertView != null && !(convertView instanceof TextView)
? convertView :
LayoutInflater.from(getContext()).inflate(R.layout.my_spinner_row, parent, false);
position = position - 1; // Adjust for initial selection item
MyModel item = getItem(position);
// ... Resolve views & populate with data ...
return row;
}
}
That's it. Note that if you use a OnItemSelectedListener
with your Spinner, in onItemSelected()
you'd also have to adjust position
to take the default item into account, for example:
if (position == 0) {
return;
} else {
position = position - 1;
}
MyModel selected = items.get(position);
edited May 23 '17 at 12:02
Community♦
11
11
answered Jan 13 '17 at 15:02
JonikJonik
52.1k55210317
52.1k55210317
1
I like this idea, don't know why it had only one vote.
– Omaraf
Mar 23 '17 at 3:07
I haven't got it working yet...I'm just a newbie...I don't have "R.layout.my_spinner_row". Where do I get this from or what do I put instead?
– Tim Cooper
Feb 10 '18 at 6:17
add a comment |
1
I like this idea, don't know why it had only one vote.
– Omaraf
Mar 23 '17 at 3:07
I haven't got it working yet...I'm just a newbie...I don't have "R.layout.my_spinner_row". Where do I get this from or what do I put instead?
– Tim Cooper
Feb 10 '18 at 6:17
1
1
I like this idea, don't know why it had only one vote.
– Omaraf
Mar 23 '17 at 3:07
I like this idea, don't know why it had only one vote.
– Omaraf
Mar 23 '17 at 3:07
I haven't got it working yet...I'm just a newbie...I don't have "R.layout.my_spinner_row". Where do I get this from or what do I put instead?
– Tim Cooper
Feb 10 '18 at 6:17
I haven't got it working yet...I'm just a newbie...I don't have "R.layout.my_spinner_row". Where do I get this from or what do I put instead?
– Tim Cooper
Feb 10 '18 at 6:17
add a comment |
In my case, although size '2' is displayed in the spinner, nothing happens till some selection is done!
I have an xml file (data_sizes.xml) which lists all the spinner values.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="chunks">
<item>2</item>
<item>4</item>
<item>8</item>
<item>16</item>
<item>32</item>
</string-array>
</resources>
In main.xml file: Spinner element
<Spinner android:id="@+id/spinnerSize"
android:layout_marginLeft="50px"
android:layout_width="fill_parent"
android:drawSelectorOnTop="true"
android:layout_marginTop="5dip"
android:prompt="@string/SelectSize"
android:layout_marginRight="30px"
android:layout_height="35px" />
Then in my java code, I added:
In my activity: Declaration
Spinner spinnerSize;
ArrayAdapter adapter;
In a public void function - initControls(): Definition
spinnerSize = (Spinner)findViewById(R.id.spinnerSize);
adapter = ArrayAdapter.createFromResource(this, R.array.chunks, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSize.setAdapter(adapter);
spinnerSize.setOnItemSelectedListener(new MyOnItemSelectedListener());
My spinner listener:
/* Spinner Listener */
class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
chunkSize = new Integer(parent.getItemAtPosition(pos).toString()).intValue();
}
public void onNothingSelected(AdapterView<?> parent) {
// Dummy
}
}
add a comment |
In my case, although size '2' is displayed in the spinner, nothing happens till some selection is done!
I have an xml file (data_sizes.xml) which lists all the spinner values.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="chunks">
<item>2</item>
<item>4</item>
<item>8</item>
<item>16</item>
<item>32</item>
</string-array>
</resources>
In main.xml file: Spinner element
<Spinner android:id="@+id/spinnerSize"
android:layout_marginLeft="50px"
android:layout_width="fill_parent"
android:drawSelectorOnTop="true"
android:layout_marginTop="5dip"
android:prompt="@string/SelectSize"
android:layout_marginRight="30px"
android:layout_height="35px" />
Then in my java code, I added:
In my activity: Declaration
Spinner spinnerSize;
ArrayAdapter adapter;
In a public void function - initControls(): Definition
spinnerSize = (Spinner)findViewById(R.id.spinnerSize);
adapter = ArrayAdapter.createFromResource(this, R.array.chunks, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSize.setAdapter(adapter);
spinnerSize.setOnItemSelectedListener(new MyOnItemSelectedListener());
My spinner listener:
/* Spinner Listener */
class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
chunkSize = new Integer(parent.getItemAtPosition(pos).toString()).intValue();
}
public void onNothingSelected(AdapterView<?> parent) {
// Dummy
}
}
add a comment |
In my case, although size '2' is displayed in the spinner, nothing happens till some selection is done!
I have an xml file (data_sizes.xml) which lists all the spinner values.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="chunks">
<item>2</item>
<item>4</item>
<item>8</item>
<item>16</item>
<item>32</item>
</string-array>
</resources>
In main.xml file: Spinner element
<Spinner android:id="@+id/spinnerSize"
android:layout_marginLeft="50px"
android:layout_width="fill_parent"
android:drawSelectorOnTop="true"
android:layout_marginTop="5dip"
android:prompt="@string/SelectSize"
android:layout_marginRight="30px"
android:layout_height="35px" />
Then in my java code, I added:
In my activity: Declaration
Spinner spinnerSize;
ArrayAdapter adapter;
In a public void function - initControls(): Definition
spinnerSize = (Spinner)findViewById(R.id.spinnerSize);
adapter = ArrayAdapter.createFromResource(this, R.array.chunks, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSize.setAdapter(adapter);
spinnerSize.setOnItemSelectedListener(new MyOnItemSelectedListener());
My spinner listener:
/* Spinner Listener */
class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
chunkSize = new Integer(parent.getItemAtPosition(pos).toString()).intValue();
}
public void onNothingSelected(AdapterView<?> parent) {
// Dummy
}
}
In my case, although size '2' is displayed in the spinner, nothing happens till some selection is done!
I have an xml file (data_sizes.xml) which lists all the spinner values.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="chunks">
<item>2</item>
<item>4</item>
<item>8</item>
<item>16</item>
<item>32</item>
</string-array>
</resources>
In main.xml file: Spinner element
<Spinner android:id="@+id/spinnerSize"
android:layout_marginLeft="50px"
android:layout_width="fill_parent"
android:drawSelectorOnTop="true"
android:layout_marginTop="5dip"
android:prompt="@string/SelectSize"
android:layout_marginRight="30px"
android:layout_height="35px" />
Then in my java code, I added:
In my activity: Declaration
Spinner spinnerSize;
ArrayAdapter adapter;
In a public void function - initControls(): Definition
spinnerSize = (Spinner)findViewById(R.id.spinnerSize);
adapter = ArrayAdapter.createFromResource(this, R.array.chunks, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSize.setAdapter(adapter);
spinnerSize.setOnItemSelectedListener(new MyOnItemSelectedListener());
My spinner listener:
/* Spinner Listener */
class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
chunkSize = new Integer(parent.getItemAtPosition(pos).toString()).intValue();
}
public void onNothingSelected(AdapterView<?> parent) {
// Dummy
}
}
answered Jan 18 '11 at 17:49
TheCottonSilkTheCottonSilk
6,78922237
6,78922237
add a comment |
add a comment |
Using a custom spinner layout like this:
<?xml version="1.0" encoding="utf-8"?>
<Spinner xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/spinnerTarget"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="14dp"
android:textColor="#000000"/>
In the activity:
// populate the list
ArrayList<String> dataList = new ArrayList<String>();
for (int i = 0; i < 4; i++) {
dataList.add("Item");
}
// set custom layout spinner_layout.xml and adapter
Spinner spinnerObject = (Spinner) findViewById(R.id.spinnerObject);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, R.drawable.spinner_layout, dataList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerObject.setAdapter(dataAdapter);
spinnerObject.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// to set value of first selection, because setOnItemSelectedListener will not dispatch if the user selects first element
TextView spinnerTarget = (TextView)v.findViewById(R.id.spinnerTarget);
spinnerTarget.setText(spinnerObject.getSelectedItem().toString());
return false;
}
});
spinnerObject.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
private boolean selectionControl = true;
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
// just the first time
if(selectionControl){
// find TextView in layout
TextView spinnerTarget = (TextView)parent.findViewById(R.id.spinnerTarget);
// set spinner text empty
spinnerTarget.setText("");
selectionControl = false;
}
else{
// select object
}
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
add a comment |
Using a custom spinner layout like this:
<?xml version="1.0" encoding="utf-8"?>
<Spinner xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/spinnerTarget"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="14dp"
android:textColor="#000000"/>
In the activity:
// populate the list
ArrayList<String> dataList = new ArrayList<String>();
for (int i = 0; i < 4; i++) {
dataList.add("Item");
}
// set custom layout spinner_layout.xml and adapter
Spinner spinnerObject = (Spinner) findViewById(R.id.spinnerObject);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, R.drawable.spinner_layout, dataList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerObject.setAdapter(dataAdapter);
spinnerObject.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// to set value of first selection, because setOnItemSelectedListener will not dispatch if the user selects first element
TextView spinnerTarget = (TextView)v.findViewById(R.id.spinnerTarget);
spinnerTarget.setText(spinnerObject.getSelectedItem().toString());
return false;
}
});
spinnerObject.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
private boolean selectionControl = true;
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
// just the first time
if(selectionControl){
// find TextView in layout
TextView spinnerTarget = (TextView)parent.findViewById(R.id.spinnerTarget);
// set spinner text empty
spinnerTarget.setText("");
selectionControl = false;
}
else{
// select object
}
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
add a comment |
Using a custom spinner layout like this:
<?xml version="1.0" encoding="utf-8"?>
<Spinner xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/spinnerTarget"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="14dp"
android:textColor="#000000"/>
In the activity:
// populate the list
ArrayList<String> dataList = new ArrayList<String>();
for (int i = 0; i < 4; i++) {
dataList.add("Item");
}
// set custom layout spinner_layout.xml and adapter
Spinner spinnerObject = (Spinner) findViewById(R.id.spinnerObject);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, R.drawable.spinner_layout, dataList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerObject.setAdapter(dataAdapter);
spinnerObject.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// to set value of first selection, because setOnItemSelectedListener will not dispatch if the user selects first element
TextView spinnerTarget = (TextView)v.findViewById(R.id.spinnerTarget);
spinnerTarget.setText(spinnerObject.getSelectedItem().toString());
return false;
}
});
spinnerObject.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
private boolean selectionControl = true;
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
// just the first time
if(selectionControl){
// find TextView in layout
TextView spinnerTarget = (TextView)parent.findViewById(R.id.spinnerTarget);
// set spinner text empty
spinnerTarget.setText("");
selectionControl = false;
}
else{
// select object
}
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
Using a custom spinner layout like this:
<?xml version="1.0" encoding="utf-8"?>
<Spinner xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/spinnerTarget"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="14dp"
android:textColor="#000000"/>
In the activity:
// populate the list
ArrayList<String> dataList = new ArrayList<String>();
for (int i = 0; i < 4; i++) {
dataList.add("Item");
}
// set custom layout spinner_layout.xml and adapter
Spinner spinnerObject = (Spinner) findViewById(R.id.spinnerObject);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, R.drawable.spinner_layout, dataList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerObject.setAdapter(dataAdapter);
spinnerObject.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// to set value of first selection, because setOnItemSelectedListener will not dispatch if the user selects first element
TextView spinnerTarget = (TextView)v.findViewById(R.id.spinnerTarget);
spinnerTarget.setText(spinnerObject.getSelectedItem().toString());
return false;
}
});
spinnerObject.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
private boolean selectionControl = true;
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
// just the first time
if(selectionControl){
// find TextView in layout
TextView spinnerTarget = (TextView)parent.findViewById(R.id.spinnerTarget);
// set spinner text empty
spinnerTarget.setText("");
selectionControl = false;
}
else{
// select object
}
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
edited Oct 26 '14 at 1:02
answered Jul 7 '12 at 6:30
gtsgts
474166
474166
add a comment |
add a comment |
Merge this:
private long previousItemId = 0;
@Override
public long getItemId(int position) {
long nextItemId = random.nextInt(Integer.MAX_VALUE);
while(previousItemId == nextItemId) {
nextItemId = random.nextInt(Integer.MAX_VALUE);
}
previousItemId = nextItemId;
return nextItemId;
}
With this answer:
public class SpinnerInteractionListener
implements AdapterView.OnItemSelectedListener, View.OnTouchListener {
private AdapterView.OnItemSelectedListener onItemSelectedListener;
public SpinnerInteractionListener(AdapterView.OnItemSelectedListener selectedListener) {
this.onItemSelectedListener = selectedListener;
}
boolean userSelect = false;
@Override
public boolean onTouch(View v, MotionEvent event) {
userSelect = true;
return false;
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if(userSelect) {
onItemSelectedListener.onItemSelected(parent, view, pos, id);
userSelect = false;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
if(userSelect) {
onItemSelectedListener.onNothingSelected(parent);
userSelect = false;
}
}
}
add a comment |
Merge this:
private long previousItemId = 0;
@Override
public long getItemId(int position) {
long nextItemId = random.nextInt(Integer.MAX_VALUE);
while(previousItemId == nextItemId) {
nextItemId = random.nextInt(Integer.MAX_VALUE);
}
previousItemId = nextItemId;
return nextItemId;
}
With this answer:
public class SpinnerInteractionListener
implements AdapterView.OnItemSelectedListener, View.OnTouchListener {
private AdapterView.OnItemSelectedListener onItemSelectedListener;
public SpinnerInteractionListener(AdapterView.OnItemSelectedListener selectedListener) {
this.onItemSelectedListener = selectedListener;
}
boolean userSelect = false;
@Override
public boolean onTouch(View v, MotionEvent event) {
userSelect = true;
return false;
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if(userSelect) {
onItemSelectedListener.onItemSelected(parent, view, pos, id);
userSelect = false;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
if(userSelect) {
onItemSelectedListener.onNothingSelected(parent);
userSelect = false;
}
}
}
add a comment |
Merge this:
private long previousItemId = 0;
@Override
public long getItemId(int position) {
long nextItemId = random.nextInt(Integer.MAX_VALUE);
while(previousItemId == nextItemId) {
nextItemId = random.nextInt(Integer.MAX_VALUE);
}
previousItemId = nextItemId;
return nextItemId;
}
With this answer:
public class SpinnerInteractionListener
implements AdapterView.OnItemSelectedListener, View.OnTouchListener {
private AdapterView.OnItemSelectedListener onItemSelectedListener;
public SpinnerInteractionListener(AdapterView.OnItemSelectedListener selectedListener) {
this.onItemSelectedListener = selectedListener;
}
boolean userSelect = false;
@Override
public boolean onTouch(View v, MotionEvent event) {
userSelect = true;
return false;
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if(userSelect) {
onItemSelectedListener.onItemSelected(parent, view, pos, id);
userSelect = false;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
if(userSelect) {
onItemSelectedListener.onNothingSelected(parent);
userSelect = false;
}
}
}
Merge this:
private long previousItemId = 0;
@Override
public long getItemId(int position) {
long nextItemId = random.nextInt(Integer.MAX_VALUE);
while(previousItemId == nextItemId) {
nextItemId = random.nextInt(Integer.MAX_VALUE);
}
previousItemId = nextItemId;
return nextItemId;
}
With this answer:
public class SpinnerInteractionListener
implements AdapterView.OnItemSelectedListener, View.OnTouchListener {
private AdapterView.OnItemSelectedListener onItemSelectedListener;
public SpinnerInteractionListener(AdapterView.OnItemSelectedListener selectedListener) {
this.onItemSelectedListener = selectedListener;
}
boolean userSelect = false;
@Override
public boolean onTouch(View v, MotionEvent event) {
userSelect = true;
return false;
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if(userSelect) {
onItemSelectedListener.onItemSelected(parent, view, pos, id);
userSelect = false;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
if(userSelect) {
onItemSelectedListener.onNothingSelected(parent);
userSelect = false;
}
}
}
edited May 23 '17 at 11:54
Community♦
11
11
answered Jun 6 '16 at 16:34
EpicPandaForceEpicPandaForce
49.4k14132255
49.4k14132255
add a comment |
add a comment |
you can put the first cell in your array to be empty({"","some","some",...})
and do nothing if the position is 0;
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(position>0) {
label.setText(MainActivity.questions[position - 1]);
}
}
- if you fill the array by xml file you can let the first item empty
add a comment |
you can put the first cell in your array to be empty({"","some","some",...})
and do nothing if the position is 0;
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(position>0) {
label.setText(MainActivity.questions[position - 1]);
}
}
- if you fill the array by xml file you can let the first item empty
add a comment |
you can put the first cell in your array to be empty({"","some","some",...})
and do nothing if the position is 0;
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(position>0) {
label.setText(MainActivity.questions[position - 1]);
}
}
- if you fill the array by xml file you can let the first item empty
you can put the first cell in your array to be empty({"","some","some",...})
and do nothing if the position is 0;
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(position>0) {
label.setText(MainActivity.questions[position - 1]);
}
}
- if you fill the array by xml file you can let the first item empty
answered Nov 8 '15 at 16:13
khaled_alokbykhaled_alokby
613
613
add a comment |
add a comment |
My solution, in case you have a TextView as each row of the spinner:
// TODO: add a fake item as the last one of "items"
final ArrayAdapter<String> adapter=new ArrayAdapter<String>(..,..,items)
{
@Override
public View getDropDownView(final int position,final View convertView,final ViewGroup parent)
{
final View dropDownView=super.getDropDownView(position,convertView,parent);
((TextView)dropDownView.findViewById(android.R.id.text1)).setHeight(position==getCount()-1?0:getDimensionFromAttribute(..,R.attr.dropdownListPreferredItemHeight));
dropDownView.getLayoutParams().height=position==getCount()-1?0:LayoutParams.MATCH_PARENT;
return dropDownView;
}
}
...
spinner.setAdapter(adapter);
_actionModeSpinnerView.setSelection(dataAdapter.getCount()-1,false);
public static int getDimensionFromAttribute(final Context context,final int attr)
{
final TypedValue typedValue=new TypedValue();
if(context.getTheme().resolveAttribute(attr,typedValue,true))
return TypedValue.complexToDimensionPixelSize(typedValue.data,context.getResources().getDisplayMetrics());
return 0;
}
add a comment |
My solution, in case you have a TextView as each row of the spinner:
// TODO: add a fake item as the last one of "items"
final ArrayAdapter<String> adapter=new ArrayAdapter<String>(..,..,items)
{
@Override
public View getDropDownView(final int position,final View convertView,final ViewGroup parent)
{
final View dropDownView=super.getDropDownView(position,convertView,parent);
((TextView)dropDownView.findViewById(android.R.id.text1)).setHeight(position==getCount()-1?0:getDimensionFromAttribute(..,R.attr.dropdownListPreferredItemHeight));
dropDownView.getLayoutParams().height=position==getCount()-1?0:LayoutParams.MATCH_PARENT;
return dropDownView;
}
}
...
spinner.setAdapter(adapter);
_actionModeSpinnerView.setSelection(dataAdapter.getCount()-1,false);
public static int getDimensionFromAttribute(final Context context,final int attr)
{
final TypedValue typedValue=new TypedValue();
if(context.getTheme().resolveAttribute(attr,typedValue,true))
return TypedValue.complexToDimensionPixelSize(typedValue.data,context.getResources().getDisplayMetrics());
return 0;
}
add a comment |
My solution, in case you have a TextView as each row of the spinner:
// TODO: add a fake item as the last one of "items"
final ArrayAdapter<String> adapter=new ArrayAdapter<String>(..,..,items)
{
@Override
public View getDropDownView(final int position,final View convertView,final ViewGroup parent)
{
final View dropDownView=super.getDropDownView(position,convertView,parent);
((TextView)dropDownView.findViewById(android.R.id.text1)).setHeight(position==getCount()-1?0:getDimensionFromAttribute(..,R.attr.dropdownListPreferredItemHeight));
dropDownView.getLayoutParams().height=position==getCount()-1?0:LayoutParams.MATCH_PARENT;
return dropDownView;
}
}
...
spinner.setAdapter(adapter);
_actionModeSpinnerView.setSelection(dataAdapter.getCount()-1,false);
public static int getDimensionFromAttribute(final Context context,final int attr)
{
final TypedValue typedValue=new TypedValue();
if(context.getTheme().resolveAttribute(attr,typedValue,true))
return TypedValue.complexToDimensionPixelSize(typedValue.data,context.getResources().getDisplayMetrics());
return 0;
}
My solution, in case you have a TextView as each row of the spinner:
// TODO: add a fake item as the last one of "items"
final ArrayAdapter<String> adapter=new ArrayAdapter<String>(..,..,items)
{
@Override
public View getDropDownView(final int position,final View convertView,final ViewGroup parent)
{
final View dropDownView=super.getDropDownView(position,convertView,parent);
((TextView)dropDownView.findViewById(android.R.id.text1)).setHeight(position==getCount()-1?0:getDimensionFromAttribute(..,R.attr.dropdownListPreferredItemHeight));
dropDownView.getLayoutParams().height=position==getCount()-1?0:LayoutParams.MATCH_PARENT;
return dropDownView;
}
}
...
spinner.setAdapter(adapter);
_actionModeSpinnerView.setSelection(dataAdapter.getCount()-1,false);
public static int getDimensionFromAttribute(final Context context,final int attr)
{
final TypedValue typedValue=new TypedValue();
if(context.getTheme().resolveAttribute(attr,typedValue,true))
return TypedValue.complexToDimensionPixelSize(typedValue.data,context.getResources().getDisplayMetrics());
return 0;
}
edited Dec 4 '15 at 23:57
answered Dec 4 '15 at 23:45
android developerandroid developer
54k98466869
54k98466869
add a comment |
add a comment |
Base on @Jonik answer I have created fully functional extension to ArrayAdapter
class SpinnerArrayAdapter<T> : ArrayAdapter<T> {
private val selectText : String
private val resource: Int
private val fieldId : Int
private val inflater : LayoutInflater
constructor(context: Context?, resource: Int, objects: Array<T>, selectText : String? = null) : super(context, resource, objects) {
this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
this.resource = resource
this.fieldId = 0
this.inflater = LayoutInflater.from(context)
}
constructor(context: Context?, resource : Int, objects: List<T>, selectText : String? = null) : super(context, resource, objects) {
this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
this.resource = resource
this.fieldId = 0
this.inflater = LayoutInflater.from(context)
}
constructor(context: Context?, resource: Int, textViewResourceId: Int, objects: Array<T>, selectText : String? = null) : super(context, resource, textViewResourceId, objects) {
this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
this.resource = resource
this.fieldId = textViewResourceId
this.inflater = LayoutInflater.from(context)
}
constructor(context: Context?, resource : Int, textViewResourceId: Int, objects: List<T>, selectText : String? = null) : super(context, resource, textViewResourceId, objects) {
this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
this.resource = resource
this.fieldId = textViewResourceId
this.inflater = LayoutInflater.from(context)
}
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup?): View {
if(position == 0) {
return initialSelection(true)
}
return createViewFromResource(inflater, position -1, convertView, parent, resource)
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
if(position == 0) {
return initialSelection(false)
}
return createViewFromResource(inflater, position -1, convertView, parent, resource)
}
override fun getCount(): Int {
return super.getCount() + 1 // adjust for initial selection
}
private fun initialSelection(inDropDown: Boolean) : View {
// Just simple TextView as initial selection.
val view = TextView(context)
view.setText(selectText)
view.setPadding(8, 0, 8, 0)
if(inDropDown) {
// Hide when dropdown is open
view.height = 0
}
return view
}
private fun createViewFromResource(inflater: LayoutInflater, position: Int,
@Nullable convertView: View?, parent: ViewGroup?, resource: Int): View {
val view: View
val text: TextView?
if (convertView == null || (convertView is TextView)) {
view = inflater.inflate(resource, parent, false)
} else {
view = convertView
}
try {
if (fieldId === 0) {
// If no custom field is assigned, assume the whole resource is a TextView
text = view as TextView
} else {
// Otherwise, find the TextView field within the layout
text = view.findViewById(fieldId)
if (text == null) {
throw RuntimeException("Failed to find view with ID "
+ context.getResources().getResourceName(fieldId)
+ " in item layout")
}
}
} catch (e: ClassCastException) {
Log.e("ArrayAdapter", "You must supply a resource ID for a TextView")
throw IllegalStateException(
"ArrayAdapter requires the resource ID to be a TextView", e)
}
val item = getItem(position)
if (item is CharSequence) {
text.text = item
} else {
text.text = item!!.toString()
}
return view
}
add a comment |
Base on @Jonik answer I have created fully functional extension to ArrayAdapter
class SpinnerArrayAdapter<T> : ArrayAdapter<T> {
private val selectText : String
private val resource: Int
private val fieldId : Int
private val inflater : LayoutInflater
constructor(context: Context?, resource: Int, objects: Array<T>, selectText : String? = null) : super(context, resource, objects) {
this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
this.resource = resource
this.fieldId = 0
this.inflater = LayoutInflater.from(context)
}
constructor(context: Context?, resource : Int, objects: List<T>, selectText : String? = null) : super(context, resource, objects) {
this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
this.resource = resource
this.fieldId = 0
this.inflater = LayoutInflater.from(context)
}
constructor(context: Context?, resource: Int, textViewResourceId: Int, objects: Array<T>, selectText : String? = null) : super(context, resource, textViewResourceId, objects) {
this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
this.resource = resource
this.fieldId = textViewResourceId
this.inflater = LayoutInflater.from(context)
}
constructor(context: Context?, resource : Int, textViewResourceId: Int, objects: List<T>, selectText : String? = null) : super(context, resource, textViewResourceId, objects) {
this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
this.resource = resource
this.fieldId = textViewResourceId
this.inflater = LayoutInflater.from(context)
}
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup?): View {
if(position == 0) {
return initialSelection(true)
}
return createViewFromResource(inflater, position -1, convertView, parent, resource)
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
if(position == 0) {
return initialSelection(false)
}
return createViewFromResource(inflater, position -1, convertView, parent, resource)
}
override fun getCount(): Int {
return super.getCount() + 1 // adjust for initial selection
}
private fun initialSelection(inDropDown: Boolean) : View {
// Just simple TextView as initial selection.
val view = TextView(context)
view.setText(selectText)
view.setPadding(8, 0, 8, 0)
if(inDropDown) {
// Hide when dropdown is open
view.height = 0
}
return view
}
private fun createViewFromResource(inflater: LayoutInflater, position: Int,
@Nullable convertView: View?, parent: ViewGroup?, resource: Int): View {
val view: View
val text: TextView?
if (convertView == null || (convertView is TextView)) {
view = inflater.inflate(resource, parent, false)
} else {
view = convertView
}
try {
if (fieldId === 0) {
// If no custom field is assigned, assume the whole resource is a TextView
text = view as TextView
} else {
// Otherwise, find the TextView field within the layout
text = view.findViewById(fieldId)
if (text == null) {
throw RuntimeException("Failed to find view with ID "
+ context.getResources().getResourceName(fieldId)
+ " in item layout")
}
}
} catch (e: ClassCastException) {
Log.e("ArrayAdapter", "You must supply a resource ID for a TextView")
throw IllegalStateException(
"ArrayAdapter requires the resource ID to be a TextView", e)
}
val item = getItem(position)
if (item is CharSequence) {
text.text = item
} else {
text.text = item!!.toString()
}
return view
}
add a comment |
Base on @Jonik answer I have created fully functional extension to ArrayAdapter
class SpinnerArrayAdapter<T> : ArrayAdapter<T> {
private val selectText : String
private val resource: Int
private val fieldId : Int
private val inflater : LayoutInflater
constructor(context: Context?, resource: Int, objects: Array<T>, selectText : String? = null) : super(context, resource, objects) {
this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
this.resource = resource
this.fieldId = 0
this.inflater = LayoutInflater.from(context)
}
constructor(context: Context?, resource : Int, objects: List<T>, selectText : String? = null) : super(context, resource, objects) {
this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
this.resource = resource
this.fieldId = 0
this.inflater = LayoutInflater.from(context)
}
constructor(context: Context?, resource: Int, textViewResourceId: Int, objects: Array<T>, selectText : String? = null) : super(context, resource, textViewResourceId, objects) {
this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
this.resource = resource
this.fieldId = textViewResourceId
this.inflater = LayoutInflater.from(context)
}
constructor(context: Context?, resource : Int, textViewResourceId: Int, objects: List<T>, selectText : String? = null) : super(context, resource, textViewResourceId, objects) {
this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
this.resource = resource
this.fieldId = textViewResourceId
this.inflater = LayoutInflater.from(context)
}
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup?): View {
if(position == 0) {
return initialSelection(true)
}
return createViewFromResource(inflater, position -1, convertView, parent, resource)
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
if(position == 0) {
return initialSelection(false)
}
return createViewFromResource(inflater, position -1, convertView, parent, resource)
}
override fun getCount(): Int {
return super.getCount() + 1 // adjust for initial selection
}
private fun initialSelection(inDropDown: Boolean) : View {
// Just simple TextView as initial selection.
val view = TextView(context)
view.setText(selectText)
view.setPadding(8, 0, 8, 0)
if(inDropDown) {
// Hide when dropdown is open
view.height = 0
}
return view
}
private fun createViewFromResource(inflater: LayoutInflater, position: Int,
@Nullable convertView: View?, parent: ViewGroup?, resource: Int): View {
val view: View
val text: TextView?
if (convertView == null || (convertView is TextView)) {
view = inflater.inflate(resource, parent, false)
} else {
view = convertView
}
try {
if (fieldId === 0) {
// If no custom field is assigned, assume the whole resource is a TextView
text = view as TextView
} else {
// Otherwise, find the TextView field within the layout
text = view.findViewById(fieldId)
if (text == null) {
throw RuntimeException("Failed to find view with ID "
+ context.getResources().getResourceName(fieldId)
+ " in item layout")
}
}
} catch (e: ClassCastException) {
Log.e("ArrayAdapter", "You must supply a resource ID for a TextView")
throw IllegalStateException(
"ArrayAdapter requires the resource ID to be a TextView", e)
}
val item = getItem(position)
if (item is CharSequence) {
text.text = item
} else {
text.text = item!!.toString()
}
return view
}
Base on @Jonik answer I have created fully functional extension to ArrayAdapter
class SpinnerArrayAdapter<T> : ArrayAdapter<T> {
private val selectText : String
private val resource: Int
private val fieldId : Int
private val inflater : LayoutInflater
constructor(context: Context?, resource: Int, objects: Array<T>, selectText : String? = null) : super(context, resource, objects) {
this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
this.resource = resource
this.fieldId = 0
this.inflater = LayoutInflater.from(context)
}
constructor(context: Context?, resource : Int, objects: List<T>, selectText : String? = null) : super(context, resource, objects) {
this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
this.resource = resource
this.fieldId = 0
this.inflater = LayoutInflater.from(context)
}
constructor(context: Context?, resource: Int, textViewResourceId: Int, objects: Array<T>, selectText : String? = null) : super(context, resource, textViewResourceId, objects) {
this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
this.resource = resource
this.fieldId = textViewResourceId
this.inflater = LayoutInflater.from(context)
}
constructor(context: Context?, resource : Int, textViewResourceId: Int, objects: List<T>, selectText : String? = null) : super(context, resource, textViewResourceId, objects) {
this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
this.resource = resource
this.fieldId = textViewResourceId
this.inflater = LayoutInflater.from(context)
}
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup?): View {
if(position == 0) {
return initialSelection(true)
}
return createViewFromResource(inflater, position -1, convertView, parent, resource)
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
if(position == 0) {
return initialSelection(false)
}
return createViewFromResource(inflater, position -1, convertView, parent, resource)
}
override fun getCount(): Int {
return super.getCount() + 1 // adjust for initial selection
}
private fun initialSelection(inDropDown: Boolean) : View {
// Just simple TextView as initial selection.
val view = TextView(context)
view.setText(selectText)
view.setPadding(8, 0, 8, 0)
if(inDropDown) {
// Hide when dropdown is open
view.height = 0
}
return view
}
private fun createViewFromResource(inflater: LayoutInflater, position: Int,
@Nullable convertView: View?, parent: ViewGroup?, resource: Int): View {
val view: View
val text: TextView?
if (convertView == null || (convertView is TextView)) {
view = inflater.inflate(resource, parent, false)
} else {
view = convertView
}
try {
if (fieldId === 0) {
// If no custom field is assigned, assume the whole resource is a TextView
text = view as TextView
} else {
// Otherwise, find the TextView field within the layout
text = view.findViewById(fieldId)
if (text == null) {
throw RuntimeException("Failed to find view with ID "
+ context.getResources().getResourceName(fieldId)
+ " in item layout")
}
}
} catch (e: ClassCastException) {
Log.e("ArrayAdapter", "You must supply a resource ID for a TextView")
throw IllegalStateException(
"ArrayAdapter requires the resource ID to be a TextView", e)
}
val item = getItem(position)
if (item is CharSequence) {
text.text = item
} else {
text.text = item!!.toString()
}
return view
}
answered Aug 10 '18 at 8:34
Michał ZiobroMichał Ziobro
1,52012234
1,52012234
add a comment |
add a comment |
I assume that you want to have a Spinner
with first empty invisible item (that is a strange feature of Spinner
that cannot show a list without selecting an item). You should add a class that will contain data:
data class YourData(val id: Int, val name: String?)
This is the adapter.
class YourAdapter(
context: Context,
private val textViewResourceId: Int,
private var items: ArrayList<YourData>
) : ArrayAdapter<YourData>(context, textViewResourceId, items) {
private var inflater: LayoutInflater = context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
override fun getCount(): Int = items.size + 1
override fun getItem(position: Int): YourData? =
if (position == 0) YourData(0, "") else items[position - 1]
override fun getItemId(position: Int): Long = position.toLong()
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View =
if (position == 0) {
getFirstTextView(convertView)
} else {
getTextView(convertView, parent, position - 1)
}
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View =
getView(position, convertView, parent)
private fun getFirstTextView(convertView: View?): View {
// Just simple TextView as initial selection.
var textView: TextView? = convertView as? TextView
val holder: FirstViewHolder
if (textView?.tag !is FirstViewHolder) {
textView = TextView(context) // inflater.inflate(R.layout.your_text, parent, false) as TextView
textView.height = 0 // Hide first item.
holder = FirstViewHolder()
holder.textView = textView
textView.tag = holder
}
return textView
}
private fun getTextView(
convertView: View?,
parent: ViewGroup,
position: Int
): TextView {
var textView: TextView? = convertView as? TextView
val holder: ViewHolder
if (textView?.tag is ViewHolder) {
holder = textView.tag as ViewHolder
} else {
textView = inflater.inflate(textViewResourceId, parent, false) as TextView
holder = ViewHolder()
holder.textView = textView
textView.tag = holder
}
holder.textView.text = items[position].name
return textView
}
private class FirstViewHolder {
lateinit var textView: TextView
}
private class ViewHolder {
lateinit var textView: TextView
}
}
To create:
YourAdapter(context!!, R.layout.text_item, ArrayList())
To add items:
private fun fill(items: List<YourData>, adapter: YourAdapter) {
adapter.run {
clear()
addAll(items)
notifyDataSetChanged()
}
}
When you load items to your Spinner
with that fill()
command, you should know, that indices are also incremented. So if you wish to select 3rd item, you should now select 4th: spinner?.setSelection(index + 1)
add a comment |
I assume that you want to have a Spinner
with first empty invisible item (that is a strange feature of Spinner
that cannot show a list without selecting an item). You should add a class that will contain data:
data class YourData(val id: Int, val name: String?)
This is the adapter.
class YourAdapter(
context: Context,
private val textViewResourceId: Int,
private var items: ArrayList<YourData>
) : ArrayAdapter<YourData>(context, textViewResourceId, items) {
private var inflater: LayoutInflater = context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
override fun getCount(): Int = items.size + 1
override fun getItem(position: Int): YourData? =
if (position == 0) YourData(0, "") else items[position - 1]
override fun getItemId(position: Int): Long = position.toLong()
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View =
if (position == 0) {
getFirstTextView(convertView)
} else {
getTextView(convertView, parent, position - 1)
}
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View =
getView(position, convertView, parent)
private fun getFirstTextView(convertView: View?): View {
// Just simple TextView as initial selection.
var textView: TextView? = convertView as? TextView
val holder: FirstViewHolder
if (textView?.tag !is FirstViewHolder) {
textView = TextView(context) // inflater.inflate(R.layout.your_text, parent, false) as TextView
textView.height = 0 // Hide first item.
holder = FirstViewHolder()
holder.textView = textView
textView.tag = holder
}
return textView
}
private fun getTextView(
convertView: View?,
parent: ViewGroup,
position: Int
): TextView {
var textView: TextView? = convertView as? TextView
val holder: ViewHolder
if (textView?.tag is ViewHolder) {
holder = textView.tag as ViewHolder
} else {
textView = inflater.inflate(textViewResourceId, parent, false) as TextView
holder = ViewHolder()
holder.textView = textView
textView.tag = holder
}
holder.textView.text = items[position].name
return textView
}
private class FirstViewHolder {
lateinit var textView: TextView
}
private class ViewHolder {
lateinit var textView: TextView
}
}
To create:
YourAdapter(context!!, R.layout.text_item, ArrayList())
To add items:
private fun fill(items: List<YourData>, adapter: YourAdapter) {
adapter.run {
clear()
addAll(items)
notifyDataSetChanged()
}
}
When you load items to your Spinner
with that fill()
command, you should know, that indices are also incremented. So if you wish to select 3rd item, you should now select 4th: spinner?.setSelection(index + 1)
add a comment |
I assume that you want to have a Spinner
with first empty invisible item (that is a strange feature of Spinner
that cannot show a list without selecting an item). You should add a class that will contain data:
data class YourData(val id: Int, val name: String?)
This is the adapter.
class YourAdapter(
context: Context,
private val textViewResourceId: Int,
private var items: ArrayList<YourData>
) : ArrayAdapter<YourData>(context, textViewResourceId, items) {
private var inflater: LayoutInflater = context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
override fun getCount(): Int = items.size + 1
override fun getItem(position: Int): YourData? =
if (position == 0) YourData(0, "") else items[position - 1]
override fun getItemId(position: Int): Long = position.toLong()
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View =
if (position == 0) {
getFirstTextView(convertView)
} else {
getTextView(convertView, parent, position - 1)
}
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View =
getView(position, convertView, parent)
private fun getFirstTextView(convertView: View?): View {
// Just simple TextView as initial selection.
var textView: TextView? = convertView as? TextView
val holder: FirstViewHolder
if (textView?.tag !is FirstViewHolder) {
textView = TextView(context) // inflater.inflate(R.layout.your_text, parent, false) as TextView
textView.height = 0 // Hide first item.
holder = FirstViewHolder()
holder.textView = textView
textView.tag = holder
}
return textView
}
private fun getTextView(
convertView: View?,
parent: ViewGroup,
position: Int
): TextView {
var textView: TextView? = convertView as? TextView
val holder: ViewHolder
if (textView?.tag is ViewHolder) {
holder = textView.tag as ViewHolder
} else {
textView = inflater.inflate(textViewResourceId, parent, false) as TextView
holder = ViewHolder()
holder.textView = textView
textView.tag = holder
}
holder.textView.text = items[position].name
return textView
}
private class FirstViewHolder {
lateinit var textView: TextView
}
private class ViewHolder {
lateinit var textView: TextView
}
}
To create:
YourAdapter(context!!, R.layout.text_item, ArrayList())
To add items:
private fun fill(items: List<YourData>, adapter: YourAdapter) {
adapter.run {
clear()
addAll(items)
notifyDataSetChanged()
}
}
When you load items to your Spinner
with that fill()
command, you should know, that indices are also incremented. So if you wish to select 3rd item, you should now select 4th: spinner?.setSelection(index + 1)
I assume that you want to have a Spinner
with first empty invisible item (that is a strange feature of Spinner
that cannot show a list without selecting an item). You should add a class that will contain data:
data class YourData(val id: Int, val name: String?)
This is the adapter.
class YourAdapter(
context: Context,
private val textViewResourceId: Int,
private var items: ArrayList<YourData>
) : ArrayAdapter<YourData>(context, textViewResourceId, items) {
private var inflater: LayoutInflater = context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
override fun getCount(): Int = items.size + 1
override fun getItem(position: Int): YourData? =
if (position == 0) YourData(0, "") else items[position - 1]
override fun getItemId(position: Int): Long = position.toLong()
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View =
if (position == 0) {
getFirstTextView(convertView)
} else {
getTextView(convertView, parent, position - 1)
}
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View =
getView(position, convertView, parent)
private fun getFirstTextView(convertView: View?): View {
// Just simple TextView as initial selection.
var textView: TextView? = convertView as? TextView
val holder: FirstViewHolder
if (textView?.tag !is FirstViewHolder) {
textView = TextView(context) // inflater.inflate(R.layout.your_text, parent, false) as TextView
textView.height = 0 // Hide first item.
holder = FirstViewHolder()
holder.textView = textView
textView.tag = holder
}
return textView
}
private fun getTextView(
convertView: View?,
parent: ViewGroup,
position: Int
): TextView {
var textView: TextView? = convertView as? TextView
val holder: ViewHolder
if (textView?.tag is ViewHolder) {
holder = textView.tag as ViewHolder
} else {
textView = inflater.inflate(textViewResourceId, parent, false) as TextView
holder = ViewHolder()
holder.textView = textView
textView.tag = holder
}
holder.textView.text = items[position].name
return textView
}
private class FirstViewHolder {
lateinit var textView: TextView
}
private class ViewHolder {
lateinit var textView: TextView
}
}
To create:
YourAdapter(context!!, R.layout.text_item, ArrayList())
To add items:
private fun fill(items: List<YourData>, adapter: YourAdapter) {
adapter.run {
clear()
addAll(items)
notifyDataSetChanged()
}
}
When you load items to your Spinner
with that fill()
command, you should know, that indices are also incremented. So if you wish to select 3rd item, you should now select 4th: spinner?.setSelection(index + 1)
edited Nov 20 '18 at 12:37
answered Nov 20 '18 at 7:49
CoolMindCoolMind
4,02213473
4,02213473
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4726490%2fhow-to-set-spinner-default-value-to-null%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Check for stackoverflow.com/questions/867518/… Especially answer 40. Work like magic!
– iftach barshem
Jan 16 '14 at 14:13
I posted a really nice solution to this here: stackoverflow.com/a/39923282/681122
– Steven L
Oct 7 '16 at 18:01
Check out aaronvargas answer here: stackoverflow.com/questions/867518/…
– live-love
Mar 9 '18 at 18:30