How does the checkbox know its association with the textview - android

I am coding a checklist on android, following an example from a textbook.
The ListActivity consists of a listview (R.layout.PCheckList) where each row has a checkbox and a textview locked inside a horizontal layout (R.layout.lchecklist).
There is a line of the code which I totally do NOT understand
The code is below, and the i've highlighted the line
public class PChecklist extends ListActivity {
TextView selection;
String[] tasks={"Do Laundry",
"Wash Dishes",
"Make the bed",
"Study",
"Buy Groceries",
"Mow the lawn",
"Shave",
"Iron Clothes",
"Breathe periodically"};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.pchecklist);
this.selection = (TextView) findViewById(R.id.selection2);
ArrayList<DailyTask> dailyTaskListModel = new ArrayList<DailyTask>();
for(String t:tasks)
{
dailyTaskListModel.add(new DailyTask(t));
}
this.setListAdapter(new CheckListAdapter(this,dailyTaskListModel));
}
private DailyTask getTaskAt(int position)
{
return ((CheckListAdapter)getListAdapter()).getItem(position);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
this.selection.setText(String.format("Selection: %s", getTaskAt(position).toString()));
}
class DailyTask
{
String task;
boolean isCompleted = false;
DailyTask(String task)
{
this.task = task;
}
public String toString()
{
if(this.isCompleted)
return (task.toUpperCase());
else return (task);
}
}
class CheckListAdapter extends ArrayAdapter<DailyTask>
{
Activity activity;
CheckListAdapter(Activity context,ArrayList<DailyTask> taskList)
{
super(context, R.layout.lchecklist,taskList);
this.activity = context;
}
public View getView(int position, View convertView, ViewGroup parent) {
View recycledView = convertView;
CheckListViewAccessor checkListViewAccessor=null;
CheckBox checkbox;
if(recycledView==null)
{
//if there is no view, we have to make one by inflating a layout.
LayoutInflater inflater = activity.getLayoutInflater();
recycledView = inflater.inflate(R.layout.lchecklist, null,false);
checkListViewAccessor = new CheckListViewAccessor(recycledView);
recycledView.setTag(recycledView);
checkbox = checkListViewAccessor.getCheckBox();
CompoundButton.OnCheckedChangeListener checkStateChangedListener = new CompoundButton.OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton cb, boolean isChecked) {
//When the check button is pressed, we want two things to happen.
//1. Update the model.
//for some reason we have to do this.
int positionOfCheckedItem = (Integer) cb.getTag();
DailyTask task = getTaskAt(positionOfCheckedItem);
task.isCompleted = isChecked;
//2. Change the String in the row to upper case.
cb.setText(task.toString());
}
};
checkbox.setOnCheckedChangeListener(checkStateChangedListener);
}else//if recycledView is not null, then we don't need to add a listener, we just need to get access to the UI components
{
checkListViewAccessor = (CheckListViewAccessor) recycledView.getTag();
checkbox = checkListViewAccessor.getCheckBox();
}
DailyTask task = getTaskAt(position);
checkbox.setTag(new Integer(position));
**checkbox.setText(task.toString());
//^This line I don't get.**
checkbox.setChecked(task.isCompleted);
return (recycledView);
}
}
class CheckListViewAccessor
{
View checkListView;
CheckBox checkbox=null;
CheckListViewAccessor(View checkListView)
{
this.checkListView = checkListView;
}
CheckBox getCheckBox()
{
if(checkbox==null)
this.checkbox = (CheckBox) findViewById(R.id.checkbox);
return (checkbox);
}
}
}
In the line indicated, how does the checkbox know which TextView's text to change? When was this relationship established?

There is no associated TextView with CheckBox. Because CheckBox is a TextView. Take a look at hierarchy here:
ava.lang.Object
↳ android.view.View
↳ android.widget.TextView
↳ android.widget.Button
↳ android.widget.CompoundButton
↳ android.widget.CheckBox
In other words CheckBox is a TextView with additional state management for checked and unchecked. (In fact CompoundButton is responsible for state management, but those are details).

The relationship is established by the adapter. For each list element, the "checkbox" object corresponds to the actual list element's checkbox. This means it's very easy to modify the Views of the list elements, and in extension it's very tricky to alter another element from within a particular element in the getView().
You might think of it this way; in the adapter - for every getView() - the current element will be seen as "local variables" from your point of view. You won´t have to bother about all global elements at this time.

Related

Toggle button in ListView changes State on Scrolling

I think I have searched through all the posts relating to my question but could not find a solution to my problem. I have A ListView with two textviews and one Toggle button. Toggle button Changes its state when I scroll up or down (go out of view). I am using viewholder (suggested on the forum) that does make the button to retain its state but then the recycling property comes into play and mess up my application i.e multiple toggle buttons change their state on one click.
What I want?
I want my toggle button to retain its previous state when it goes out of view and comes back plus when I click one toggle button only that toggle button should work.
Here is my Code for Listview (pardon me for not putting much comments)
public class ActivityB extends AppCompatActivity {
ListView list;
Button edit;
public String text= "";
public SharedPreferences.Editor editor;
public SharedPreferences sharedPreferences;
private ArrayList<String> data = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_b);
list = (ListView) findViewById(R.id.listView);
generateListContent();
list.setAdapter(new MyListadapter(this,R.layout.constraint,data));
edit= (Button) findViewById(R.id.button);
sharedPreferences=getSharedPreferences("MyData",Context.MODE_PRIVATE);
editor=sharedPreferences.edit();
text=sharedPreferences.getString("Text","Null");
//Toast.makeText(this,text,Toast.LENGTH_LONG).show();
}
public void generateListContent() {
for (int i = 0; i < 11; i++) {
data.add("This is item no " + i);
}
}
private class MyListadapter extends ArrayAdapter<String> {
private int layout;
ArrayList<String> list;
public MyListadapter(#NonNull Context context, #LayoutRes int resource, #NonNull List<String> objects) {
super(context, resource, objects);
layout=resource;
list= (ArrayList<String>) objects;
}
#NonNull
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
ViewHolder mainviewHolder=null;
if(convertView==null){
LayoutInflater inflater=LayoutInflater.from(getContext());
convertView= inflater.inflate(layout,parent,false);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.title= (TextView) convertView.findViewById(R.id.textView);
viewHolder.lastone= (TextView) convertView.findViewById(R.id.textView2);
viewHolder.button= (ToggleButton) convertView.findViewById(R.id.toggleButton);
//mainviewHolder.title.setText(getItem(position));
viewHolder.button.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
buttonView.setChecked(true);
Toast.makeText(getContext(), "Button is On" + position , Toast.LENGTH_LONG).show();
} else {
buttonView.setChecked(false);
Toast.makeText(getContext(), "Button is OFF" + position + buttonView.getId(),Toast.LENGTH_LONG).show();
}
}
});
convertView.setTag(viewHolder);
}
else{
mainviewHolder = (ViewHolder) convertView.getTag();
mainviewHolder.title.setText(getItem(position));
}
return convertView;
}
}
public class ViewHolder{
TextView title;
TextView lastone;
ToggleButton button;
}
}
check this...
Recyclerview Changing Items During Scroll
if above does not work....
Method 1
things you can try...
1.check button status outside toggle method....so that every time the listviewe loaded it can assign a value rather no value.
create a method togglebtn(viewHolder) // pass the instance of this perticualr item
Inside togglebtn....modify the toggle btn by reference with the instance.
togglebtn(viewHolder v)
{
}
Method 2
create a public data structure to hold the status of the button....preferebaly hasmap to store item no+check status....then check this value every time and update.
Feel free to ask.
Instead of creating array list of strings, create a custom object something like below.
Class A {
public String title;
public boolean isChecked;
}
Set correct value to isChecked(true/false) depending on toggle button state.
Also add one more line inside getview()
button.setChecked(list.get(position).isChecked)
Thanks Everyone for sparing your time and answering my question.
With these answers and a little help from forum' other posts, I found a solution.
Since I have a limited number of views so i removed the if/else condition on layout inflater. This solved the reuse of position variable. Now every view object has a unique position. Secondly the random button status behavior is resolved by saving the toggle button state in a separate array and keeping it outside my getview() method.

How to set default text in spinner? [duplicate]

I want to use a Spinner that initially (when the user has not made a selection yet) displays the text "Select One". When the user clicks the spinner, the list of items is displayed and the user selects one of the options. After the user has made a selection, the selected item is displayed in the Spinner instead of "Select One".
I have the following code to create a Spinner:
String[] items = new String[] {"One", "Two", "Three"};
Spinner spinner = (Spinner) findViewById(R.id.mySpinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
With this code, initially the item "One" is displayed. I could just add a new item "Select One" to the items, but then "Select One" would also be displayed in the dropdown list as first item, which is not what I want.
How can I fix this problem?
What you can do is decorate your SpinnerAdapter with one that presents a 'Select Option...' View initially for the Spinner to display with nothing selected.
Here is a working example tested for Android 2.3, and 4.0 (it uses nothing in the compatibility library, so it should be fine for awhile) Since it's a decorator, it should be easy to retrofit existing code and it works fine with CursorLoaders also. (Swap cursor on the wrapped cursorAdapter of course...)
There is an Android bug that makes this a little tougher to re-use views. (So you have to use the setTag or something else to ensure your convertView is correct.) Spinner does not support multiple view types
Code notes: 2 constructors
This allows you to use a standard prompt or define your own 'nothing selected' as the first row, or both, or none. (Note: Some themes show a DropDown for a Spinner instead of a dialog. The Dropdown doesn't normally show the prompt)
You define a layout to 'look' like a prompt, for example, grayed out...
Using a standard prompt (notice that nothing is selected):
Or with a prompt and something dynamic (could have had no prompt also):
Usage in above example
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.planets_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setPrompt("Select your favorite Planet!");
spinner.setAdapter(
new NothingSelectedSpinnerAdapter(
adapter,
R.layout.contact_spinner_row_nothing_selected,
// R.layout.contact_spinner_nothing_selected_dropdown, // Optional
this));
contact_spinner_row_nothing_selected.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/text1"
style="?android:attr/spinnerItemStyle"
android:singleLine="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:textSize="18sp"
android:textColor="#808080"
android:text="[Select a Planet...]" />
NothingSelectedSpinnerAdapter.java
import android.content.Context;
import android.database.DataSetObserver;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.SpinnerAdapter;
/**
* Decorator Adapter to allow a Spinner to show a 'Nothing Selected...' initially
* displayed instead of the first choice in the Adapter.
*/
public class NothingSelectedSpinnerAdapter implements SpinnerAdapter, ListAdapter {
protected static final int EXTRA = 1;
protected SpinnerAdapter adapter;
protected Context context;
protected int nothingSelectedLayout;
protected int nothingSelectedDropdownLayout;
protected LayoutInflater layoutInflater;
/**
* Use this constructor to have NO 'Select One...' item, instead use
* the standard prompt or nothing at all.
* #param spinnerAdapter wrapped Adapter.
* #param nothingSelectedLayout layout for nothing selected, perhaps
* you want text grayed out like a prompt...
* #param context
*/
public NothingSelectedSpinnerAdapter(
SpinnerAdapter spinnerAdapter,
int nothingSelectedLayout, Context context) {
this(spinnerAdapter, nothingSelectedLayout, -1, context);
}
/**
* Use this constructor to Define your 'Select One...' layout as the first
* row in the returned choices.
* If you do this, you probably don't want a prompt on your spinner or it'll
* have two 'Select' rows.
* #param spinnerAdapter wrapped Adapter. Should probably return false for isEnabled(0)
* #param nothingSelectedLayout layout for nothing selected, perhaps you want
* text grayed out like a prompt...
* #param nothingSelectedDropdownLayout layout for your 'Select an Item...' in
* the dropdown.
* #param context
*/
public NothingSelectedSpinnerAdapter(SpinnerAdapter spinnerAdapter,
int nothingSelectedLayout, int nothingSelectedDropdownLayout, Context context) {
this.adapter = spinnerAdapter;
this.context = context;
this.nothingSelectedLayout = nothingSelectedLayout;
this.nothingSelectedDropdownLayout = nothingSelectedDropdownLayout;
layoutInflater = LayoutInflater.from(context);
}
#Override
public final View getView(int position, View convertView, ViewGroup parent) {
// This provides the View for the Selected Item in the Spinner, not
// the dropdown (unless dropdownView is not set).
if (position == 0) {
return getNothingSelectedView(parent);
}
return adapter.getView(position - EXTRA, null, parent); // Could re-use
// the convertView if possible.
}
/**
* View to show in Spinner with Nothing Selected
* Override this to do something dynamic... e.g. "37 Options Found"
* #param parent
* #return
*/
protected View getNothingSelectedView(ViewGroup parent) {
return layoutInflater.inflate(nothingSelectedLayout, parent, false);
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
// Android BUG! http://code.google.com/p/android/issues/detail?id=17128 -
// Spinner does not support multiple view types
if (position == 0) {
return nothingSelectedDropdownLayout == -1 ?
new View(context) :
getNothingSelectedDropdownView(parent);
}
// Could re-use the convertView if possible, use setTag...
return adapter.getDropDownView(position - EXTRA, null, parent);
}
/**
* Override this to do something dynamic... For example, "Pick your favorite
* of these 37".
* #param parent
* #return
*/
protected View getNothingSelectedDropdownView(ViewGroup parent) {
return layoutInflater.inflate(nothingSelectedDropdownLayout, parent, false);
}
#Override
public int getCount() {
int count = adapter.getCount();
return count == 0 ? 0 : count + EXTRA;
}
#Override
public Object getItem(int position) {
return position == 0 ? null : adapter.getItem(position - EXTRA);
}
#Override
public int getItemViewType(int position) {
return 0;
}
#Override
public int getViewTypeCount() {
return 1;
}
#Override
public long getItemId(int position) {
return position >= EXTRA ? adapter.getItemId(position - EXTRA) : position - EXTRA;
}
#Override
public boolean hasStableIds() {
return adapter.hasStableIds();
}
#Override
public boolean isEmpty() {
return adapter.isEmpty();
}
#Override
public void registerDataSetObserver(DataSetObserver observer) {
adapter.registerDataSetObserver(observer);
}
#Override
public void unregisterDataSetObserver(DataSetObserver observer) {
adapter.unregisterDataSetObserver(observer);
}
#Override
public boolean areAllItemsEnabled() {
return false;
}
#Override
public boolean isEnabled(int position) {
return position != 0; // Don't allow the 'nothing selected'
// item to be picked.
}
}
Here's a general solution that overrides the Spinner view. It overrides setAdapter() to set the initial position to -1, and proxies the supplied SpinnerAdapter to display the prompt string for position less than 0.
This has been tested on Android 1.5 through 4.2, but buyer beware! Because this solution relies on reflection to call the private AdapterView.setNextSelectedPositionInt() and AdapterView.setSelectedPositionInt(), it's not guaranteed to work in future OS updates. It seems likely that it will, but it is by no means guaranteed.
Normally I wouldn't condone something like this, but this question has been asked enough times and it seems like a reasonable enough request that I thought I would post my solution.
/**
* A modified Spinner that doesn't automatically select the first entry in the list.
*
* Shows the prompt if nothing is selected.
*
* Limitations: does not display prompt if the entry list is empty.
*/
public class NoDefaultSpinner extends Spinner {
public NoDefaultSpinner(Context context) {
super(context);
}
public NoDefaultSpinner(Context context, AttributeSet attrs) {
super(context, attrs);
}
public NoDefaultSpinner(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
public void setAdapter(SpinnerAdapter orig ) {
final SpinnerAdapter adapter = newProxy(orig);
super.setAdapter(adapter);
try {
final Method m = AdapterView.class.getDeclaredMethod(
"setNextSelectedPositionInt",int.class);
m.setAccessible(true);
m.invoke(this,-1);
final Method n = AdapterView.class.getDeclaredMethod(
"setSelectedPositionInt",int.class);
n.setAccessible(true);
n.invoke(this,-1);
}
catch( Exception e ) {
throw new RuntimeException(e);
}
}
protected SpinnerAdapter newProxy(SpinnerAdapter obj) {
return (SpinnerAdapter) java.lang.reflect.Proxy.newProxyInstance(
obj.getClass().getClassLoader(),
new Class[]{SpinnerAdapter.class},
new SpinnerAdapterProxy(obj));
}
/**
* Intercepts getView() to display the prompt if position < 0
*/
protected class SpinnerAdapterProxy implements InvocationHandler {
protected SpinnerAdapter obj;
protected Method getView;
protected SpinnerAdapterProxy(SpinnerAdapter obj) {
this.obj = obj;
try {
this.getView = SpinnerAdapter.class.getMethod(
"getView",int.class,View.class,ViewGroup.class);
}
catch( Exception e ) {
throw new RuntimeException(e);
}
}
public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
try {
return m.equals(getView) &&
(Integer)(args[0])<0 ?
getView((Integer)args[0],(View)args[1],(ViewGroup)args[2]) :
m.invoke(obj, args);
}
catch (InvocationTargetException e) {
throw e.getTargetException();
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
protected View getView(int position, View convertView, ViewGroup parent)
throws IllegalAccessException {
if( position<0 ) {
final TextView v =
(TextView) ((LayoutInflater)getContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE)).inflate(
android.R.layout.simple_spinner_item,parent,false);
v.setText(getPrompt());
return v;
}
return obj.getView(position,convertView,parent);
}
}
}
I ended up using a Button instead. While a Button is not a Spinner, the behavior is easy to customize.
First create the Adapter as usual:
String[] items = new String[] {"One", "Two", "Three"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, items);
Note that I am using the simple_spinner_dropdown_item as the layout id. This will help create a better look when creating the alert dialog.
In the onClick handler for my Button I have:
public void onClick(View w) {
new AlertDialog.Builder(this)
.setTitle("the prompt")
.setAdapter(adapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO: user specific action
dialog.dismiss();
}
}).create().show();
}
And that's it!
First, you might be interested in the prompt attribute of the Spinner class. See the picture below, "Choose a Planet" is the prompt that can be set in the XML with android:prompt="".
I was going to suggest subclassing Spinner, where you could maintain two adapters internally. One adapter that has the "Select One" option, and the other real adapter (with the actual options), then using the OnClickListener to switch the adapters before the choices dialog is shown. However, after trying implement that idea I've come to the conclusion you cannot receive OnClick events for the widget itself.
You could wrap the spinner in a different view, intercept the clicks on the view, and then tell your CustomSpinner to switch the adapter, but seems like an awful hack.
Do you really need to show "Select One"?
This code has been tested and works on Android 4.4
Spinner spinner = (Spinner) activity.findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(activity, android.R.layout.simple_spinner_dropdown_item) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
if (position == getCount()) {
((TextView)v.findViewById(android.R.id.text1)).setText("");
((TextView)v.findViewById(android.R.id.text1)).setHint(getItem(getCount())); //"Hint to be displayed"
}
return v;
}
#Override
public int getCount() {
return super.getCount()-1; // you dont display last item. It is used as hint.
}
};
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter.add("Daily");
adapter.add("Two Days");
adapter.add("Weekly");
adapter.add("Monthly");
adapter.add("Three Months");
adapter.add("HINT_TEXT_HERE"); //This is the text that will be displayed as hint.
spinner.setAdapter(adapter);
spinner.setSelection(adapter.getCount()); //set the hint the default selection so it appears on launch.
spinner.setOnItemSelectedListener(this);
I found this solution:
String[] items = new String[] {"Select One", "Two", "Three"};
Spinner spinner = (Spinner) findViewById(R.id.mySpinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
items[0] = "One";
selectedItem = items[position];
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
Just change the array[0] with "Select One" and then in the onItemSelected, rename it to "One".
Not a classy solution, but it works :D
Lots of answers here but I'm surprised no one suggested a simple solution: Place a TextView on top of the Spinner. Set a click listener on the TextView which hides the TextView shows the Spinner, and calls spinner.performClick().
There is no default API to set hint on Spinner. To add it we need a small workaround with out that not safety reflection implementation
List<Object> objects = new ArrayList<Object>();
objects.add(firstItem);
objects.add(secondItem);
// add hint as last item
objects.add(hint);
HintAdapter adapter = new HintAdapter(context, objects, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner spinnerFilmType = (Spinner) findViewById(R.id.spinner);
spinner.setAdapter(adapter);
// show hint
spinner.setSelection(adapter.getCount());
Adapter source:
public class HintAdapter
extends ArrayAdapter<Objects> {
public HintAdapter(Context theContext, List<Object> objects) {
super(theContext, android.R.id.text1, android.R.id.text1, objects);
}
public HintAdapter(Context theContext, List<Object> objects, int theLayoutResId) {
super(theContext, theLayoutResId, android.R.id.text1, objects);
}
#Override
public int getCount() {
// don't display last item. It is used as hint.
int count = super.getCount();
return count > 0 ? count - 1 : count;
}
}
Original source
I got the same problem for spinner, with an empty selection, and I found a better solution. Have a look at this simple code.
Spinner lCreditOrDebit = (Spinner)lCardPayView.findViewById(R.id.CARD_TYPE);
spinneradapter lAdapter =
new spinneradapter(
BillPayScreen.this,
ndroid.R.layout.simple_spinner_item,getResources().getStringArray(R.array.creditordebit));
lAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
lCreditOrDebit.setAdapter(lAdapter);
Here spinneradapter is a small customization for arrayadapter. It looks like this:
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
public class spinneradapter extends ArrayAdapter<String>{
private Context m_cContext;
public spinneradapter(Context context,int textViewResourceId, String[] objects) {
super(context, textViewResourceId, objects);
this.m_cContext = context;
}
boolean firsttime = true;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(firsttime){
firsttime = false;
//Just return some empty view
return new ImageView(m_cContext);
}
//Let the array adapter take care of it this time.
return super.getView(position, convertView, parent);
}
}
You can change it to a Text View and use this:
android:style="#android:style/Widget.DeviceDefault.Light.Spinner"
and then define the android:text property.
XML file:
<Spinner android:id="#+id/locationSpinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="#string/select_location" />
Activity:
private Spinner featuresSelection;
private ArrayAdapter<CharSequence> featuresAdapter;
private List<CharSequence> featuresList;
onCreate:
featuresList = new ArrayList<CharSequence>();
featuresAdapter = new ArrayAdapter<CharSequence>(this,
android.R.layout.simple_spinner_item, featuresList);
featuresAdapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
featuresSelection = ((Spinner) yourActivity.this
.findViewById(R.id.locationSpinner));
featuresSelection.setAdapter(featuresAdapter);
featuresSelection.setOnItemSelectedListener(
new MyOnItemSelectedListener());
Some function (add things to the adapter programmatically)>
featuresAdapter.add("some string");
Now you have an empty spinner and you can write code to not open the dialog if empty. Or they can press back. But you also populate it with a function or another list during run time.
In addition, There is a simple trick to show default:
You can add a default value in your list and then add all of your collection using list.addAll(yourCollection);
Sample workable code here:
List<FuelName> fuelList = new ArrayList<FuelName>();
fuelList.add(new FuelName(0,"Select One"));
fuelList.addAll(response.body());
ArrayAdapter adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item, fuelList);
//fuelName.setPrompt("Select Fuel");
fuelName.setAdapter(adapter);
I have a spinner on my main.xml and its id is #+id/spinner1
this is what i write in my OnCreate function :
spinner1 = (Spinner)this.findViewById(R.id.spinner1);
final String[] groupes = new String[] {"A", "B", "C", "D", "E", "F", "G", "H"};
ArrayAdapter<CharSequence> featuresAdapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, new ArrayList<CharSequence>());
featuresAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(featuresAdapter);
for (String s : groupes) featuresAdapter.add(s);
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
// Here go your instructions when the user chose something
Toast.makeText(getBaseContext(), groupes[position], 0).show();
}
public void onNothingSelected(AdapterView<?> arg0) { }
});
It doesn't need any implementation in the class.
I have tried like the following. Take a button and give the click event to it. By changing the button background, it seems to be a spinner.
Declare as global variables alertdialog and default value..
AlertDialog d;
static int default_value = 0;
final Button btn = (Button) findViewById(R.id.button1);
btn .setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
//c.show();
final CharSequence str[] = {"Android","Black Berry","Iphone"};
AlertDialog.Builder builder =
new AlertDialog.Builder(TestGalleryActivity.this).setSingleChoiceItems(
str, default_value,new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int position)
{
Toast.makeText(TestGalleryActivity.this,
"" + position,
Toast.LENGTH_SHORT).show();
default_value = position;
btn.setText(str[position]);
if(d.isShowing())
d.dismiss();
}
}).setTitle("Select Any");
d = builder.create();
d.show();
}
});
Take a look at the iosched app for a general purpose solution to adding an element to the top of a list. In particular, if you are using a CursorAdapter, look at TracksAdapter.java which extends that definition to provide a "setHasAllItem" method and associated code to manage the list count to deal with the extra item at the top.
Using the custom adapter you can set the text to "Select One" or whatever else you may want that top item to say.
I found many good solutions for this. most is working by adding an item to the end of adapter, and don't display the last item in drop-down list.
The big problem for me was the spinner drop-down list will start from the bottom of the list. So user see the last items instead of the first items (in case of have many items to show), after touch the spinner for the first time.
So I put the hint item to the beginning of the list. and hide the first item in drop-down list.
private void loadSpinner(){
HintArrayAdapter hintAdapter = new HintArrayAdapter<String>(context, 0);
hintAdapter.add("Hint to be displayed");
hintAdapter.add("Item 1");
hintAdapter.add("Item 2");
.
.
hintAdapter.add("Item 30");
spinner1.setAdapter(hintAdapter);
//spinner1.setSelection(0); //display hint. Actually you can ignore it, because the default is already 0
//spinner1.setSelection(0, false); //use this if don't want to onItemClick called for the hint
spinner1.setOnItemSelectedListener(yourListener);
}
private class HintArrayAdapter<T> extends ArrayAdapter<T> {
Context mContext;
public HintArrayAdapter(Context context, int resource) {
super(context, resource);
this.mContext = context
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(android.R.layout.simple_spinner_item, parent, false);
TextView texview = (TextView) view.findViewById(android.R.id.text1);
if(position == 0) {
texview.setText("");
texview.setHint(getItem(position).toString()); //"Hint to be displayed"
} else {
texview.setText(getItem(position).toString());
}
return view;
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view;
if(position == 0){
view = inflater.inflate(R.layout.spinner_hint_list_item_layout, parent, false); // Hide first row
} else {
view = inflater.inflate(android.R.layout.simple_spinner_dropdown_item, parent, false);
TextView texview = (TextView) view.findViewById(android.R.id.text1);
texview.setText(getItem(position).toString());
}
return view;
}
}
set the below layout in #Override getDropDownView() when position is 0, to hide the first hint row.
R.layout.spinner_hint_list_item_layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</LinearLayout>
I think the easiest way is creating a dummy item on index 0 saying "select one" and then on saving maybe check that selection is not 0.
So this is my final example "all-in" for a button-spinner
In activity_my_form.xml
<Button
android:id="#+id/btnSpinnerPlanets"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="left|center_vertical"
android:singleLine="true"
android:text="#string/selectAPlanet"
android:textSize="10sp"
android:background="#android:drawable/btn_dropdown">
</Button>
In strings.xml
<string name="selectAPlanet">Select planet…</string>
<string-array name="planets__entries">
<item>The Sun with a name very long so long long long long longThe Sun with a name very long so long long long long longThe Sun with a name very long so long long long long long</item>
<item>Mercury</item>
<item>Venus</item>
<item>Earth</item>
<item>Mars</item>
<item>Jupiter</item>
<item>Saturn</item>
<item>Uranus</item>
<item>Neptune</item>
</string-array>
In MyFormActivity.java
public class MyFormActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
((Button) findViewById(R.id.btnSpinnerPlanets)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String[] items = view.getResources().getStringArray(R.array.planets__entries);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MyFormActivity.this, android.R.layout.simple_spinner_dropdown_item, items);
new AlertDialog.Builder(MyFormActivity.this).setTitle("the prompt").setAdapter(adapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((Button) findViewById(R.id.btnSpinnerPlanets)).setText(items[which]);
dialog.dismiss();
}
}).create().show();
}
});
}
}
Finally I obtained a font size configurable no first item selectable button spinner!!!
Thanks to HRJ
The best solution I found for this is actually not to use a Spinner but an AutoCompleteTextView. Its basically an EditText with attached Spinner to show suggestions as you type - but, with the right config, it can behave exactly as the OP wishes and more.
XML:
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/item"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.appcompat.widget.AppCompatAutoCompleteTextView
android:id="#+id/input"
android:hint="Select one"
style="#style/AutoCompleteTextViewDropDown"/>
</com.google.android.material.textfield.TextInputLayout>
Style:
<style name="AutoCompleteTextViewDropDown">
<item name="android:clickable">false</item>
<item name="android:cursorVisible">false</item>
<item name="android:focusable">false</item>
<item name="android:focusableInTouchMode">false</item>
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
</style>
As for the adapter use the basic ArrayAdapter or extend it to make your own, but no additional customization on the adapter side is necessary. Set the adapter on the AutoCompleteTextView.
When extending SpinnerAdapter, you override two View-producing methods, getView(int, View, ViewGroup) and getDropDownView(int, View, ViewGroup). The first one supplies the View inserted into the Spinner itself; the second supplies the View in the drop-down list (as the name suggests). You can override the getView(...) so that, until an item has been selected, it displays a TextView containing a prompt; then, when you detect an item has been selected, you change it to display a TextView corresponding to that.
public class PromptingAdapter extends SpinnerAdapter {
//... various code ...
private boolean selectionmade = false;
//call this method from the OnItemSelectedListener for your Spinner
public setSelectionState(boolean b) {
selectionmade = b;
}
#Override
public View getView(int position, View recycle, ViewGroup container) {
if(selectionmade) {
//your existing code to supply a View for the Spinner
//you could even put "return getDropDownView(position, recycle, container);"
}
else {
View output;
if(recycle instanceof TextView) {
output = recycle;
}
else {
output = new TextView();
//and layout stuff
}
output.setText(R.string.please_select_one);
//put a string "please_select_one" in res/values/strings.xml
return output;
}
}
//...
}
For those using Xamarin, here is the C# equivalent to aaronvargas's answer above.
using Android.Content;
using Android.Database;
using Android.Views;
using Android.Widget;
using Java.Lang;
namespace MyNamespace.Droid
{
public class NothingSelectedSpinnerAdapter : BaseAdapter, ISpinnerAdapter, IListAdapter
{
protected static readonly int EXTRA = 1;
protected ISpinnerAdapter adapter;
protected Context context;
protected int nothingSelectedLayout;
protected int nothingSelectedDropdownLayout;
protected LayoutInflater layoutInflater;
public NothingSelectedSpinnerAdapter(ISpinnerAdapter spinnerAdapter, int nothingSelectedLayout, Context context) : this(spinnerAdapter, nothingSelectedLayout, -1, context)
{
}
public NothingSelectedSpinnerAdapter(ISpinnerAdapter spinnerAdapter, int nothingSelectedLayout, int nothingSelectedDropdownLayout, Context context)
{
this.adapter = spinnerAdapter;
this.context = context;
this.nothingSelectedLayout = nothingSelectedLayout;
this.nothingSelectedDropdownLayout = nothingSelectedDropdownLayout;
layoutInflater = LayoutInflater.From(context);
}
protected View GetNothingSelectedView(ViewGroup parent)
{
return layoutInflater.Inflate(nothingSelectedLayout, parent, false);
}
protected View GetNothingSelectedDropdownView(ViewGroup parent)
{
return layoutInflater.Inflate(nothingSelectedDropdownLayout, parent, false);
}
public override Object GetItem(int position)
{
return position == 0 ? null : adapter.GetItem(position - EXTRA);
}
public override long GetItemId(int position)
{
return position >= EXTRA ? adapter.GetItemId(position - EXTRA) : position - EXTRA;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
// This provides the View for the Selected Item in the Spinner, not
// the dropdown (unless dropdownView is not set).
if (position == 0)
{
return GetNothingSelectedView(parent);
}
// Could re-use the convertView if possible.
return this.adapter.GetView(position - EXTRA, null, parent);
}
public override int Count
{
get
{
int count = this.adapter.Count;
return count == 0 ? 0 : count + EXTRA;
}
}
public override View GetDropDownView(int position, View convertView, ViewGroup parent)
{
// Android BUG! http://code.google.com/p/android/issues/detail?id=17128 -
// Spinner does not support multiple view types
if (position == 0)
{
return nothingSelectedDropdownLayout == -1 ?
new View(context) :
GetNothingSelectedDropdownView(parent);
}
// Could re-use the convertView if possible, use setTag...
return adapter.GetDropDownView(position - EXTRA, null, parent);
}
public override int GetItemViewType(int position)
{
return 0;
}
public override int ViewTypeCount => 1;
public override bool HasStableIds => this.adapter.HasStableIds;
public override bool IsEmpty => this.adapter.IsEmpty;
public override void RegisterDataSetObserver(DataSetObserver observer)
{
adapter.RegisterDataSetObserver(observer);
}
public override void UnregisterDataSetObserver(DataSetObserver observer)
{
adapter.UnregisterDataSetObserver(observer);
}
public override bool AreAllItemsEnabled()
{
return false;
}
public override bool IsEnabled(int position)
{
return position > 0;
}
}
}
I also solved this problem by using the following code. Suppose you are having a list of items e.g.
ArrayList<Item> itemsArrayList = new ArrayList<Item>();
Item item1 = new Item();
item1.setId(1);
item1.setData("First Element");
Item item2 = new Item();
item2.setId(2);
Item2.setData("Second Element");
itemsArrayList.add(item1);
itemsArrayList.add(item2);
Now we have to provide the strings to spinner because spinner can not understand the object. So we will create an new array list with string items like this ->
ArrayList<String> itemStringArrayList = new ArrayList<String>();
for(Item item : itemsArrayList) {
itemStringArrayList.add(item.getData());
}
Now we have itemStringArrayList array list with two string items. And we have to show the "Select Item" text as first item. So we have to insert an new string into the itemStringArrayList.
itemStringArrayList.add("Select Item");
Now we have an array list itemsArrayList and we want to show two elements in the drop down. But the condition here is ...If we don't select anything then Select Item should appear as first element which will not be enabled.
So we can implement this functionality like this. If you need to load the array list items into the android spinner. So you will have to use some adapter. So here i'll use the ArrayAdapter. We can use the customise adapter too.
ArrayAdapter<String> itemsArrayAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.spinner_item, itemsArrayList){
#Override
public boolean isEnabled(int position) {
if(position == 0)
{
return false;
}
else
{
return true;
}
}
#Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
View view = super.getDropDownView(position, convertView, parent);
TextView tv = (TextView) view;
if(position == 0){
// Set the hint text color gray
tv.setTextColor(Color.GRAY);
}
else {
tv.setTextColor(Color.BLACK);
}
return view;
}
};
itemsArrayAdapter.setDropDownViewResource(R.layout.spinner_item);
your_spinner_name.setAdapter(itemsArrayAdapter);
Here in this code. we are using the customised spinner layout i.e. R.layout.spinner_item. It's a simple text view
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textStyle="italic"
android:fontFamily="sans-serif-medium"
/>
We need to disable the first text in the spinner. So for the position 0 we are disabling the text. And color also we can set by overiding getDropDownView method. So in this way we will get the expected spinner.
I was facing the same problem yesterday and did not want to add a hidden item to the ArrayAdapter or use reflections, which works fine but is kind of dirty.
After reading many posts and trying around I found a solution by extending ArrayAdapter and Overriding the getView method.
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
/**
* A SpinnerAdapter which does not show the value of the initial selection initially,
* but an initialText.
* To use the spinner with initial selection instead call notifyDataSetChanged().
*/
public class SpinnerAdapterWithInitialText<T> extends ArrayAdapter<T> {
private Context context;
private int resource;
private boolean initialTextWasShown = false;
private String initialText = "Please select";
/**
* Constructor
*
* #param context The current context.
* #param resource The resource ID for a layout file containing a TextView to use when
* instantiating views.
* #param objects The objects to represent in the ListView.
*/
public SpinnerAdapterWithInitialText(#NonNull Context context, int resource, #NonNull T[] objects) {
super(context, resource, objects);
this.context = context;
this.resource = resource;
}
/**
* Returns whether the user has selected a spinner item, or if still the initial text is shown.
* #param spinner The spinner the SpinnerAdapterWithInitialText is assigned to.
* #return true if the user has selected a spinner item, false if not.
*/
public boolean selectionMade(Spinner spinner) {
return !((TextView)spinner.getSelectedView()).getText().toString().equals(initialText);
}
/**
* Returns a TextView with the initialText the first time getView is called.
* So the Spinner has an initialText which does not represent the selected item.
* To use the spinner with initial selection instead call notifyDataSetChanged(),
* after assigning the SpinnerAdapterWithInitialText.
*/
#Override
public View getView(int position, View recycle, ViewGroup container) {
if(initialTextWasShown) {
return super.getView(position, recycle, container);
} else {
initialTextWasShown = true;
LayoutInflater inflater = LayoutInflater.from(context);
final View view = inflater.inflate(resource, container, false);
((TextView) view).setText(initialText);
return view;
}
}
}
What Android does when initialising the Spinner, is calling getView for the selected item before calling getView for all items in T[] objects.
The SpinnerAdapterWithInitialText returns a TextView with the initialText, the first time it is called.
All the other times it calls super.getView which is the getView method of ArrayAdapter which is called if you are using the Spinner normally.
To find out whether the user has selected a spinner item, or if the spinner still displays the initialText, call selectionMade and hand over the spinner the adapter is assigned to.
See the answer with lightweight and high customisable library:
https://stackoverflow.com/a/73085435/6694920
<com.innowisegroup.hintedspinner.HintedSpinner
android:id="#+id/hintedSpinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="20dp"
app:hintTextSize="24sp"
app:hintTextColor="#color/red"
app:hint="Custom hint"
app:withDivider="true"
app:dividerColor="#color/dark_green"
app:arrowDrawable="#drawable/example_arrow_4"
app:arrowTint="#color/colorAccent"
app:popupBackground="#color/light_blue"
app:items="#array/text" />
Collapsed spinner:
Expanded spinner:
I'd just use a RadioGroup with RadioButtons if you only have three choices, you can make them all unchecked at first.
None of the previously submitted answers really worked the way I wanted to solve this issue. To me the ideal solution would provide the “Select One” (or whatever initial text) when the spinner is first displayed. When the user taps the spinner, the initial text shouldn’t be a part of the drop down that is displayed.
To further complicate my particular situation, my spinner data is coming form a cursor that is loaded via the LoaderManager callbacks.
After considerable experimentation I came up with the following solution:
public class MyFragment extends Fragment implements
LoaderManager.LoaderCallbacks<Cursor>{
private static final String SPINNER_INIT_VALUE = "Select A Widget";
private Spinner mSpinner;
private int mSpinnerPosition;
private boolean mSpinnerDropDownShowing = false;
private View mSpinnerDropDown;
private MyCursorAdapter mCursorAdapter;
...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
...
mCursorAdapter = new MyCursorAdapter(getActivity());
mSpinner = (Spinner) rootView.findViewById(R.id.theSpinner);
mSpinner.setOnTouchListener(mSpinnerTouchListener);
mSpinner.setAdapter(mCursorAdapter);
...
}
//Capture the touch events to toggle the spinner's dropdown visibility
private OnTouchListener mSpinnerTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if(mSpinnerDropDown != null && mSpinnerDropDownShowing == false){
mSpinnerDropDownShowing = true;
mSpinnerDropDown.setVisibility(View.VISIBLE);
}
return false;
}
};
//Capture the click event on the spinner drop down items
protected OnClickListener spinnerItemClick = new OnClickListener(){
#Override
public void onClick(View view) {
String widget = ((TextView) view.findViewById(android.R.id.text1)).getText().toString();
if(!widget.equals(SPINNER_INIT_VALUE)){
if(mCursorAdapter != null){
Cursor cursor = mCursorAdapter.getCursor();
if(cursor.moveToFirst()){
while(!cursor.isAfterLast()){
if(widget.equals(cursor.getString(WidgetQuery.WIDGET_NAME))){
...
//Set the spinner to the correct item
mSpinnerPosition = cursor.getPosition() + 1;
mSpinner.setSelection(mSpinnerPosition);
break;
}
cursor.moveToNext();
}
}
}
}
//Hide the drop down. Not the most elegent solution but it is the only way I could hide/dismiss the drop down
mSpinnerDropDown = view.getRootView();
mSpinnerDropDownShowing = false;
mSpinnerDropDown.setVisibility(View.GONE);
}
};
private class MyCursorAdapter extends CursorAdapter {
private final int DISPLACEMENT = 1;
private final int DEFAULT_ITEM_ID = Integer.MAX_VALUE;
private Activity mActivity;
public MyCursorAdapter(Activity activity) {
super(activity, null, false);
mActivity = activity;
}
//When loading the regular views, inject the defualt item
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(position == 0){
if(convertView == null){
convertView = mActivity.getLayoutInflater().inflate(R.layout.list_item_widget, parent, false);
}
return getDefaultItem(convertView);
}
return super.getView(position - DISPLACEMENT, convertView, parent);
}
//When loading the drop down views, set the onClickListener for each view
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent){
View view = super.getDropDownView(position, convertView, parent);
view.setOnClickListener(spinnerItemClick);
return view;
}
//The special default item that is being injected
private View getDefaultItem(View convertView){
TextView text = (TextView) convertView.findViewById(android.R.id.text1);
text.setText(SPINNER_INIT_VALUE);
return convertView;
}
#Override
public long getItemId(int position) {
if (position == 0) {
return DEFAULT_ITEM_ID;
}
return super.getItemId(position - DISPLACEMENT);
}
#Override
public boolean isEnabled(int position) {
return position == 0 ? true : super.isEnabled(position - DISPLACEMENT);
}
#Override
public int getViewTypeCount() {
return super.getViewTypeCount() + DISPLACEMENT;
}
#Override
public int getItemViewType(int position) {
if (position == 0) {
return super.getViewTypeCount();
}
return super.getItemViewType(position - DISPLACEMENT);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return mActivity.getLayoutInflater().inflate(R.layout.list_item_widget, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor){
if(cursor.isAfterLast()){
return;
}
TextView text = (TextView) view.findViewById(android.R.id.text1);
String WidgetName = cursor.getString(WidgetQuery.WIDGET_NAME);
text.setText(WidgetName);
}
}
}
I handle this by using a button instead of a Spinner. I have the sample project up on GitHub.
In the project, i'm displaying both the Spinner and button to show that they indeed look identical. Except the button you can set the initial text to whatever you want.
Here's what the activity looks like:
package com.stevebergamini.spinnerbutton;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Spinner;
public class MainActivity extends Activity {
Spinner spinner1;
Button button1;
AlertDialog ad;
String[] countries;
int selected = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner1 = (Spinner) findViewById(R.id.spinner1);
button1 = (Button) findViewById(R.id.button1);
countries = getResources().getStringArray(R.array.country_names);
// You can also use an adapter for the allert dialog if you'd like
// ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, countries);
ad = new AlertDialog.Builder(MainActivity.this).setSingleChoiceItems(countries, selected,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
button1.setText(countries[which]);
selected = which;
ad.dismiss();
}}).setTitle(R.string.select_country).create();
button1.setOnClickListener( new OnClickListener(){
#Override
public void onClick(View v) {
ad.getListView().setSelection(selected);
ad.show();
}});
}
}
NOTE: Yes, I realize that this is dependent on the applied Theme and the look will be slightly different if using Theme.Holo. However, if you're using one of the legacy themes such as Theme.Black, you're good to go.
Seems a banal solution but I usually put simply a TextView in the front of the spinner. The whole Xml looks like this. (hey guys, don't shoot me, I know that some of you don't like this kind of marriage):
<FrameLayout
android:id="#+id/selectTypesLinear"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<Spinner
android:id="#+id/spinnerExercises"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:entries="#array/exercise_spinner_entries"
android:prompt="#string/exercise_spinner_prompt"
/>
<TextView
android:id="#+id/spinnerSelectText"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Hey! Select this guy!"
android:gravity="center"
android:background="#FF000000" />
</FrameLayout>
Then I hide the TextView when an Item was selected. Obviously the background color of the TextView should be the same as the Spinner. Works on Android 4.0. Don't know on older versions.
Yes. Because the Spinner calls setOnItemSelectedListener at the beginning, the hiding of the textview could be a little bit tricky, but can be done this way:
Boolean controlTouched;
exerciseSpinner.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
controlTouched = true; // I touched it but but not yet selected an Item.
return false;
}
});
exerciseSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
if (controlTouched) { // Are you sure that I touched it with my fingers and not someone else ?
spinnerSelText.setVisibility(View.GONE);
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
for me it worked something like this. has the improvement that only changes the text in SOME options, not in all.
First i take the names of the spinner and create the arrayadapter with a customize view, but it doesn't matter now, the key is override the getView, and inside change the values u need to change. In my case was only the first one, the rest i leave the original
public void rellenarSpinnerCompeticiones(){
spinnerArrayCompeticiones = new ArrayList<String>();
for(Competicion c: ((Controlador)getApplication()).getCompeticiones()){
spinnerArrayCompeticiones.add(c.getNombre());
}
//ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this,R.layout.spinner_item_competicion,spinnerArrayCompeticiones);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, R.layout.spinner_item_competicion, spinnerArrayCompeticiones){
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View v = vi.inflate(R.layout.spinner_item_competicion, null);
final TextView t = (TextView)v.findViewById(R.id.tvCompeticion);
if(spinnerCompeticion.getSelectedItemPosition()>0){
t.setText(spinnerArrayCompeticiones.get(spinnerCompeticion.getSelectedItemPosition()));
}else{
t.setText("Competiciones");
}
return v;
}
};
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerCompeticion.setAdapter(spinnerArrayAdapter);
}
Refer to one of the above answers: https://stackoverflow.com/a/23005376/1312796
I added my code to fix a little bug. That where no data retrieved..How to show the prompt text..!
Here is my Trick...It works fine with me. !
Try to put your spinner in a Relative_layoutand align a Textview with your spinner and play with the visibility of the Textview (SHOW/HIDE) whenever the adapter of the spinner loaded or empty..Like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="20dp"
android:background="#ededed"
android:orientation="vertical">
<TextView
android:id="#+id/txt_prompt_from"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:textColor="#color/gray"
android:textSize="16sp"
android:layout_alignStart="#+id/sp_from"
android:text="From"
android:visibility="gone"/>
<Spinner
android:id="#+id/sp_from"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
/>
Here is the code:
txt__from = (TextView) rootView.findViewById(R.id.txt_prompt_from);
call this method after and before spinner adapter loaded and empty.
setPromptTextViewVisibility (); //True or fales
public void setPromptTextViewVisibility (boolean visible )
{
if (visible)
{
txt_from.setVisibility(View.VISIBLE);
}
else
{
txt_from.setVisibility(View.INVISIBLE);
}
}

Strikethrough an ArrayList<String> item when long pressed

I'm trying to make a simple to-do list where you would long-press an item to mark it as 'done', in which case it will be greyed out and strikethrough.
I'm working on the strikethrough first and found some sample code here creating a strikethrough text in Android? . However the problem is that the setPaintFlags() method only seems to work on TextView whereas the items on my list are String. I can't cast a String to a TextView, and I found a workaround here but apparently it's highly discouraged to do it: Cast String to TextView . Also I looked up SpannableString but it doesn't seem to work for strings of varying length.
So I'm back at square one - is it at all possible to implement what I'm trying to do? Or will I have to store my list items differently instead?
Relevant code:
public class MainActivity extends ActionBarActivity {
private ArrayList<String> items;
private ArrayAdapter<String> itemsAdapter;
private ListView lvItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Setting what the ListView will consist of
lvItems = (ListView) findViewById(R.id.lvItems);
readItems();
itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
lvItems.setAdapter(itemsAdapter);
// Set up remove listener method call
setupListViewListener();
}
//Attaches a long click listener to the listview
private void setupListViewListener() {
lvItems.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter,
View item, int pos, long id) {
// Trying to make the onLongClick strikethrough the text
String clickedItem = items.get(pos);
//What do I do here??
// Refresh the adapter
itemsAdapter.notifyDataSetChanged();
writeItems();
// Return true consumes the long click event (marks it handled)
return true;
}
});
}
Let's take a step back and consider your app. You want to show a list of jobs to the user. Each job has a description. And each job has two possible states: 'done' or 'not done'.
So I would like to introduce a class 'Job'
class Job
{
private String mDescription;
private boolean mDone;
public Job(String description)
{
this.mDescription = description;
this.mDone = false;
}
// ... generate the usual getters and setters here ;-)
// especially:
public boolean isDone()
{
return mIsDone;
}
}
This way your ArrayList 'items' becomes be a ArrayList< Job >. Wether a job is done or not will be stored together with its description. This is important because you want to show the current state of the job to the user by changing the look of the UI element, but you need to keep track of the job's state on the data level as well.
The UI element - the TextView - will be configured to present information about the job to the user. One piece of information is the description. The TextView will store this as a String. The other piece of information is the state (done/ not done). The TextView will (in your app) store this by setting the strike-through flag and changing its color.
Because for performance reasons a ListView uses less elements than the data list ('items') contains, you have to write a custom adapter. For brevity's sake, I'm keeping the code very simple, but it's worth the time to read up on the View Holder pattern:
Let's use a layout file 'mytextviewlayout.xml' for the list rows:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/textView"/>
</LinearLayout>
Now the code for the adapter looks like this:
EDIT changed from ArrayAdapter to BaseAdapter and added a view holder (see comments):
public class MyAdapter extends BaseAdapter
{
private ArrayList<Job> mDatalist;
private int mLayoutID;
private Activity mCtx;
private MyAdapter(){} // the adapter won't work with the standard constructor
public MyAdapter(Activity context, int resource, ArrayList<Job> objects)
{
super();
mLayoutID = resource;
mDatalist = objects;
mCtx = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = mCtx.getLayoutInflater();
rowView = inflater.inflate(mLayoutID, null);
ViewHolder viewHolder = new ViewHolder();
viewHolder.tvDescription = (TextView) rowView.findViewById(R.id.textView);
rowView.setTag(viewHolder);
}
ViewHolder vholder = (ViewHolder) rowView.getTag();
TextView tvJob = vholder.tvDescription;
Job myJob = mDatalist.get(position);
tvJob.setText(myJob.getJobDescription());
if (myJob.isDone())
{
// apply changes to TextView
tvJob.setPaintFlags(tvJob.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
tvJob.setTextColor(Color.GRAY);
}
else
{
// show TextView as usual
tvJob.setPaintFlags(tvJob.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));
tvJob.setTextColor(Color.BLACK); // or whatever is needed...
}
return rowView;
}
#Override
public int getCount()
{
return mDatalist.size();
}
#Override
public Object getItem(int position)
{
return mDatalist.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
static class ViewHolder
{
public TextView tvDescription;
}
}
Due to the changed adapter,
in the MainActivity, you have to declare 'items' and 'itemsAdapter' as follows:
private ArrayList<Job> items;
private MyAdapter itemsAdapter;
...and in your 'onCreate()' method, you write:
itemsAdapter = new MyAdapter<String>(this, R.layout.mytextviewlayout, items);
Don't forget to change the 'readItems()' and 'writeItems()' methods because 'items' now is a ArrayList< Job >.
Then, finally, the 'onItemLongClick()' method:
EDIT use 'parent.getItemAtPosition()' instead of 'items.get()', see comments
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id)
{
// items.get(position).setDone(true);
Object o = parent.getItemAtPosition(position);
if (o instanceof Job)
{
((Job) o).setDone(true);
}
// and now indeed the data set has changed :)
itemsAdapter.notifyDataSetChanged();
writeItems();
return true;
}

How to get selected list items from a Listview with checkBox and Custom Adapter?

I have a ListView with CheckBox on it. and i am using Custom Adapter to populate the ListView.
In my xml file i have a Button at bottom. what i want is let user select number of rows in ListView and when he/she clicked on the Button get the position of the selected items so that i could get the object for particular row for further calculations.
In the customadapter's getview method, do
//use the actual id of your checkbox of course
Checkbox checkbox = (CheckBox)findViewById(R.id.checkbox);
checkbox.setFocusable(false);
checkbox.setFocusableInTouchMode(false);
now the checkbox is clickable as is the listitem.
To solve this problem you will have to create a custom Item class which will represent your individual checkboxes on the list. The array of these items will then be used by the adapter class to display your check boxes.
This Item class will have a boolean variable isSelected which will determine if the checkbox is selected or not. You will have to set the value of this variable in your OnClick Method of your custom adapter class
For Example
class CheckBoxItem{
boolean isSelected;
public void setSelected(boolean val) {
this.isSelected = val;
}
boolean isSelected(){
return isSelected;
}
}
For your CustomAdapter Class which look like following:
public class ItemsAdapter extends ArrayAdapter implements OnClickListener {
// you will have to initialize below in the constructor
CheckBoxItem items[];
// You will have to create your check boxes here and set the position of your check box
/// with help of setTag method of View as defined in below method, you will use this later // in your onClick method
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
CheckBox cBox = null;
if (v == null) {
LayoutInflater vi = (LayoutInflater) apUI.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.attachphoto, null);
}
CheckBoxItemItem it = items[position];
cBox =(CheckBox) v.findViewById(R.id.apCheckBox);
cBox.setOnClickListener(this);
cBox.setTag(""+position);
Log.d(TAG, " CHECK BOX IS: "+cBox+ " Check Box selected Value: "+cBox.isChecked()+" Selection: "+it.isSelected());
if(cBox != null){
cBox.setText("");
cBox.setChecked(it.isSelected());
}
return v;
}
public void onClick(View v) {
CheckBox cBox =(CheckBox) v.findViewById(R.id.apCheckBox);
int position = Integer.parseInt((String) v.getTag());
Log.d(TAG, "CLicked ..."+cBox.isChecked());
items[position].setSelected(cBox.isChecked());
}
}
Later you will will declare and array of your CheckBoxItem class which will be contained by your Adapter class in this case it will be ItemsAdapter class.
Then when the user presses the button you can iterate through all the items in the array and check which one is selected by using the isSelected() method of CheckBoxItem class.
In your activity you will have:
ArrayList getSelectedItems(){
ArrayList selectedItems = new ArrayList();
int size = items.length;
for(int i = 0; i<size; i++){
CheckBoxItem cItem = items[i];
if(cItem.isSelected()){
selectedItems.add(cItem);
}
}
return selectedItems;
}
I had the exact same problem. I solved it in this way
public class myActivity extends Activity {
//ActionBarSherlock mSherlock = ActionBarSherlock.wrap(this);
public ListView listview;
private ArrayList<Object> itemlist=new ArrayList<Object>();
Button button;
private myAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview=(ListView)findViewById(R.id.listview1);
button=(Button)findViewById(R.id.button1);
/*add some data to ur list*/ itemlist.add(something);
adapter=new Adapter(myActivity.this, 0, itemlist);
listview.setAdapter(adapter);
**listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listview.setItemsCanFocus(false);**
button.setOnClickListner(new OnClickListner()
{
#Override
public void OnClick(View v)
{
/* this returns the checked item positions in the listview*/
**ArrayList<Integer> itempositions=adapter.getcheckeditemcount();**
for(int i:itempositions)
{
/* This is the main part...u can retrieve the object in the listview which is checked and do further calculations with it*/
**Object info=adapter.getItem(i);**
Log.d(TAG,"checked object info= ",info.something);
}
}
});
}
private class myAdapter extends ArrayAdapter<Object> {
private Context context;
private ArrayList<Object> list;
**private ArrayList<Integer> checkedpositions;**
public myAdapter(Context localContext,int textViewResourceId, ArrayList<Object> objects) {
super(localContext,textViewResourceId,objects);
context = localContext;
this.list=objects;
this.checkedpositions=new ArrayList<Integer>();
//Log.d("adapter","list size= "+objects.size());
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView picturesView;
View v = convertView;
TextView Mainitem;
final CheckBox check;
if (v == null)
{
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.albumview, null);
Object item=list.get(position);
if(item!=null)
{
check = (CheckBox)v.findViewById(R.id.checkBox1);
/* set a tag for chekbox with the current view position */
**check.setTag(position);**
/*set a onchecked change listner for listning to state of checkbox toggle */
check.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
/*get the tag of the checkbox...in this case this will give the (position of view)*/
Object tag=check.getTag();
if ( isChecked )
{
// perform logic
count++;
Log.d("Checkbox","added "+tag);
checkedpositions.add((Integer) tag);
}
else
{
count--;
checkedpositions.remove(tag);
Log.d("Checkbox","removed "+(Integer)tag);
}
/* if u dont have a textview in ur listview then ignore this part */
Mainitem = (TextView) v.findViewById(R.id.textView1);
Mainitem.setText(item.Album_name);
} catch (IOException e) {
// TODO Auto-generated catch block
Log.d("error", "wall");
}
}
}
return v;
}
/* Finally create a method which return the checkeditem postions in the listview */
**public ArrayList<Integer> getcheckeditemcount()
{
return this.checkedpositions;
}**
}
}
I hope this helps.

How to make an Android Spinner with initial text "Select One"?

I want to use a Spinner that initially (when the user has not made a selection yet) displays the text "Select One". When the user clicks the spinner, the list of items is displayed and the user selects one of the options. After the user has made a selection, the selected item is displayed in the Spinner instead of "Select One".
I have the following code to create a Spinner:
String[] items = new String[] {"One", "Two", "Three"};
Spinner spinner = (Spinner) findViewById(R.id.mySpinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
With this code, initially the item "One" is displayed. I could just add a new item "Select One" to the items, but then "Select One" would also be displayed in the dropdown list as first item, which is not what I want.
How can I fix this problem?
What you can do is decorate your SpinnerAdapter with one that presents a 'Select Option...' View initially for the Spinner to display with nothing selected.
Here is a working example tested for Android 2.3, and 4.0 (it uses nothing in the compatibility library, so it should be fine for awhile) Since it's a decorator, it should be easy to retrofit existing code and it works fine with CursorLoaders also. (Swap cursor on the wrapped cursorAdapter of course...)
There is an Android bug that makes this a little tougher to re-use views. (So you have to use the setTag or something else to ensure your convertView is correct.) Spinner does not support multiple view types
Code notes: 2 constructors
This allows you to use a standard prompt or define your own 'nothing selected' as the first row, or both, or none. (Note: Some themes show a DropDown for a Spinner instead of a dialog. The Dropdown doesn't normally show the prompt)
You define a layout to 'look' like a prompt, for example, grayed out...
Using a standard prompt (notice that nothing is selected):
Or with a prompt and something dynamic (could have had no prompt also):
Usage in above example
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.planets_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setPrompt("Select your favorite Planet!");
spinner.setAdapter(
new NothingSelectedSpinnerAdapter(
adapter,
R.layout.contact_spinner_row_nothing_selected,
// R.layout.contact_spinner_nothing_selected_dropdown, // Optional
this));
contact_spinner_row_nothing_selected.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/text1"
style="?android:attr/spinnerItemStyle"
android:singleLine="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:textSize="18sp"
android:textColor="#808080"
android:text="[Select a Planet...]" />
NothingSelectedSpinnerAdapter.java
import android.content.Context;
import android.database.DataSetObserver;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.SpinnerAdapter;
/**
* Decorator Adapter to allow a Spinner to show a 'Nothing Selected...' initially
* displayed instead of the first choice in the Adapter.
*/
public class NothingSelectedSpinnerAdapter implements SpinnerAdapter, ListAdapter {
protected static final int EXTRA = 1;
protected SpinnerAdapter adapter;
protected Context context;
protected int nothingSelectedLayout;
protected int nothingSelectedDropdownLayout;
protected LayoutInflater layoutInflater;
/**
* Use this constructor to have NO 'Select One...' item, instead use
* the standard prompt or nothing at all.
* #param spinnerAdapter wrapped Adapter.
* #param nothingSelectedLayout layout for nothing selected, perhaps
* you want text grayed out like a prompt...
* #param context
*/
public NothingSelectedSpinnerAdapter(
SpinnerAdapter spinnerAdapter,
int nothingSelectedLayout, Context context) {
this(spinnerAdapter, nothingSelectedLayout, -1, context);
}
/**
* Use this constructor to Define your 'Select One...' layout as the first
* row in the returned choices.
* If you do this, you probably don't want a prompt on your spinner or it'll
* have two 'Select' rows.
* #param spinnerAdapter wrapped Adapter. Should probably return false for isEnabled(0)
* #param nothingSelectedLayout layout for nothing selected, perhaps you want
* text grayed out like a prompt...
* #param nothingSelectedDropdownLayout layout for your 'Select an Item...' in
* the dropdown.
* #param context
*/
public NothingSelectedSpinnerAdapter(SpinnerAdapter spinnerAdapter,
int nothingSelectedLayout, int nothingSelectedDropdownLayout, Context context) {
this.adapter = spinnerAdapter;
this.context = context;
this.nothingSelectedLayout = nothingSelectedLayout;
this.nothingSelectedDropdownLayout = nothingSelectedDropdownLayout;
layoutInflater = LayoutInflater.from(context);
}
#Override
public final View getView(int position, View convertView, ViewGroup parent) {
// This provides the View for the Selected Item in the Spinner, not
// the dropdown (unless dropdownView is not set).
if (position == 0) {
return getNothingSelectedView(parent);
}
return adapter.getView(position - EXTRA, null, parent); // Could re-use
// the convertView if possible.
}
/**
* View to show in Spinner with Nothing Selected
* Override this to do something dynamic... e.g. "37 Options Found"
* #param parent
* #return
*/
protected View getNothingSelectedView(ViewGroup parent) {
return layoutInflater.inflate(nothingSelectedLayout, parent, false);
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
// Android BUG! http://code.google.com/p/android/issues/detail?id=17128 -
// Spinner does not support multiple view types
if (position == 0) {
return nothingSelectedDropdownLayout == -1 ?
new View(context) :
getNothingSelectedDropdownView(parent);
}
// Could re-use the convertView if possible, use setTag...
return adapter.getDropDownView(position - EXTRA, null, parent);
}
/**
* Override this to do something dynamic... For example, "Pick your favorite
* of these 37".
* #param parent
* #return
*/
protected View getNothingSelectedDropdownView(ViewGroup parent) {
return layoutInflater.inflate(nothingSelectedDropdownLayout, parent, false);
}
#Override
public int getCount() {
int count = adapter.getCount();
return count == 0 ? 0 : count + EXTRA;
}
#Override
public Object getItem(int position) {
return position == 0 ? null : adapter.getItem(position - EXTRA);
}
#Override
public int getItemViewType(int position) {
return 0;
}
#Override
public int getViewTypeCount() {
return 1;
}
#Override
public long getItemId(int position) {
return position >= EXTRA ? adapter.getItemId(position - EXTRA) : position - EXTRA;
}
#Override
public boolean hasStableIds() {
return adapter.hasStableIds();
}
#Override
public boolean isEmpty() {
return adapter.isEmpty();
}
#Override
public void registerDataSetObserver(DataSetObserver observer) {
adapter.registerDataSetObserver(observer);
}
#Override
public void unregisterDataSetObserver(DataSetObserver observer) {
adapter.unregisterDataSetObserver(observer);
}
#Override
public boolean areAllItemsEnabled() {
return false;
}
#Override
public boolean isEnabled(int position) {
return position != 0; // Don't allow the 'nothing selected'
// item to be picked.
}
}
Here's a general solution that overrides the Spinner view. It overrides setAdapter() to set the initial position to -1, and proxies the supplied SpinnerAdapter to display the prompt string for position less than 0.
This has been tested on Android 1.5 through 4.2, but buyer beware! Because this solution relies on reflection to call the private AdapterView.setNextSelectedPositionInt() and AdapterView.setSelectedPositionInt(), it's not guaranteed to work in future OS updates. It seems likely that it will, but it is by no means guaranteed.
Normally I wouldn't condone something like this, but this question has been asked enough times and it seems like a reasonable enough request that I thought I would post my solution.
/**
* A modified Spinner that doesn't automatically select the first entry in the list.
*
* Shows the prompt if nothing is selected.
*
* Limitations: does not display prompt if the entry list is empty.
*/
public class NoDefaultSpinner extends Spinner {
public NoDefaultSpinner(Context context) {
super(context);
}
public NoDefaultSpinner(Context context, AttributeSet attrs) {
super(context, attrs);
}
public NoDefaultSpinner(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
public void setAdapter(SpinnerAdapter orig ) {
final SpinnerAdapter adapter = newProxy(orig);
super.setAdapter(adapter);
try {
final Method m = AdapterView.class.getDeclaredMethod(
"setNextSelectedPositionInt",int.class);
m.setAccessible(true);
m.invoke(this,-1);
final Method n = AdapterView.class.getDeclaredMethod(
"setSelectedPositionInt",int.class);
n.setAccessible(true);
n.invoke(this,-1);
}
catch( Exception e ) {
throw new RuntimeException(e);
}
}
protected SpinnerAdapter newProxy(SpinnerAdapter obj) {
return (SpinnerAdapter) java.lang.reflect.Proxy.newProxyInstance(
obj.getClass().getClassLoader(),
new Class[]{SpinnerAdapter.class},
new SpinnerAdapterProxy(obj));
}
/**
* Intercepts getView() to display the prompt if position < 0
*/
protected class SpinnerAdapterProxy implements InvocationHandler {
protected SpinnerAdapter obj;
protected Method getView;
protected SpinnerAdapterProxy(SpinnerAdapter obj) {
this.obj = obj;
try {
this.getView = SpinnerAdapter.class.getMethod(
"getView",int.class,View.class,ViewGroup.class);
}
catch( Exception e ) {
throw new RuntimeException(e);
}
}
public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
try {
return m.equals(getView) &&
(Integer)(args[0])<0 ?
getView((Integer)args[0],(View)args[1],(ViewGroup)args[2]) :
m.invoke(obj, args);
}
catch (InvocationTargetException e) {
throw e.getTargetException();
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
protected View getView(int position, View convertView, ViewGroup parent)
throws IllegalAccessException {
if( position<0 ) {
final TextView v =
(TextView) ((LayoutInflater)getContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE)).inflate(
android.R.layout.simple_spinner_item,parent,false);
v.setText(getPrompt());
return v;
}
return obj.getView(position,convertView,parent);
}
}
}
I ended up using a Button instead. While a Button is not a Spinner, the behavior is easy to customize.
First create the Adapter as usual:
String[] items = new String[] {"One", "Two", "Three"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, items);
Note that I am using the simple_spinner_dropdown_item as the layout id. This will help create a better look when creating the alert dialog.
In the onClick handler for my Button I have:
public void onClick(View w) {
new AlertDialog.Builder(this)
.setTitle("the prompt")
.setAdapter(adapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO: user specific action
dialog.dismiss();
}
}).create().show();
}
And that's it!
First, you might be interested in the prompt attribute of the Spinner class. See the picture below, "Choose a Planet" is the prompt that can be set in the XML with android:prompt="".
I was going to suggest subclassing Spinner, where you could maintain two adapters internally. One adapter that has the "Select One" option, and the other real adapter (with the actual options), then using the OnClickListener to switch the adapters before the choices dialog is shown. However, after trying implement that idea I've come to the conclusion you cannot receive OnClick events for the widget itself.
You could wrap the spinner in a different view, intercept the clicks on the view, and then tell your CustomSpinner to switch the adapter, but seems like an awful hack.
Do you really need to show "Select One"?
This code has been tested and works on Android 4.4
Spinner spinner = (Spinner) activity.findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(activity, android.R.layout.simple_spinner_dropdown_item) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
if (position == getCount()) {
((TextView)v.findViewById(android.R.id.text1)).setText("");
((TextView)v.findViewById(android.R.id.text1)).setHint(getItem(getCount())); //"Hint to be displayed"
}
return v;
}
#Override
public int getCount() {
return super.getCount()-1; // you dont display last item. It is used as hint.
}
};
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter.add("Daily");
adapter.add("Two Days");
adapter.add("Weekly");
adapter.add("Monthly");
adapter.add("Three Months");
adapter.add("HINT_TEXT_HERE"); //This is the text that will be displayed as hint.
spinner.setAdapter(adapter);
spinner.setSelection(adapter.getCount()); //set the hint the default selection so it appears on launch.
spinner.setOnItemSelectedListener(this);
I found this solution:
String[] items = new String[] {"Select One", "Two", "Three"};
Spinner spinner = (Spinner) findViewById(R.id.mySpinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
items[0] = "One";
selectedItem = items[position];
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
Just change the array[0] with "Select One" and then in the onItemSelected, rename it to "One".
Not a classy solution, but it works :D
Lots of answers here but I'm surprised no one suggested a simple solution: Place a TextView on top of the Spinner. Set a click listener on the TextView which hides the TextView shows the Spinner, and calls spinner.performClick().
There is no default API to set hint on Spinner. To add it we need a small workaround with out that not safety reflection implementation
List<Object> objects = new ArrayList<Object>();
objects.add(firstItem);
objects.add(secondItem);
// add hint as last item
objects.add(hint);
HintAdapter adapter = new HintAdapter(context, objects, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner spinnerFilmType = (Spinner) findViewById(R.id.spinner);
spinner.setAdapter(adapter);
// show hint
spinner.setSelection(adapter.getCount());
Adapter source:
public class HintAdapter
extends ArrayAdapter<Objects> {
public HintAdapter(Context theContext, List<Object> objects) {
super(theContext, android.R.id.text1, android.R.id.text1, objects);
}
public HintAdapter(Context theContext, List<Object> objects, int theLayoutResId) {
super(theContext, theLayoutResId, android.R.id.text1, objects);
}
#Override
public int getCount() {
// don't display last item. It is used as hint.
int count = super.getCount();
return count > 0 ? count - 1 : count;
}
}
Original source
I got the same problem for spinner, with an empty selection, and I found a better solution. Have a look at this simple code.
Spinner lCreditOrDebit = (Spinner)lCardPayView.findViewById(R.id.CARD_TYPE);
spinneradapter lAdapter =
new spinneradapter(
BillPayScreen.this,
ndroid.R.layout.simple_spinner_item,getResources().getStringArray(R.array.creditordebit));
lAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
lCreditOrDebit.setAdapter(lAdapter);
Here spinneradapter is a small customization for arrayadapter. It looks like this:
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
public class spinneradapter extends ArrayAdapter<String>{
private Context m_cContext;
public spinneradapter(Context context,int textViewResourceId, String[] objects) {
super(context, textViewResourceId, objects);
this.m_cContext = context;
}
boolean firsttime = true;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(firsttime){
firsttime = false;
//Just return some empty view
return new ImageView(m_cContext);
}
//Let the array adapter take care of it this time.
return super.getView(position, convertView, parent);
}
}
You can change it to a Text View and use this:
android:style="#android:style/Widget.DeviceDefault.Light.Spinner"
and then define the android:text property.
XML file:
<Spinner android:id="#+id/locationSpinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="#string/select_location" />
Activity:
private Spinner featuresSelection;
private ArrayAdapter<CharSequence> featuresAdapter;
private List<CharSequence> featuresList;
onCreate:
featuresList = new ArrayList<CharSequence>();
featuresAdapter = new ArrayAdapter<CharSequence>(this,
android.R.layout.simple_spinner_item, featuresList);
featuresAdapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
featuresSelection = ((Spinner) yourActivity.this
.findViewById(R.id.locationSpinner));
featuresSelection.setAdapter(featuresAdapter);
featuresSelection.setOnItemSelectedListener(
new MyOnItemSelectedListener());
Some function (add things to the adapter programmatically)>
featuresAdapter.add("some string");
Now you have an empty spinner and you can write code to not open the dialog if empty. Or they can press back. But you also populate it with a function or another list during run time.
In addition, There is a simple trick to show default:
You can add a default value in your list and then add all of your collection using list.addAll(yourCollection);
Sample workable code here:
List<FuelName> fuelList = new ArrayList<FuelName>();
fuelList.add(new FuelName(0,"Select One"));
fuelList.addAll(response.body());
ArrayAdapter adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item, fuelList);
//fuelName.setPrompt("Select Fuel");
fuelName.setAdapter(adapter);
I have a spinner on my main.xml and its id is #+id/spinner1
this is what i write in my OnCreate function :
spinner1 = (Spinner)this.findViewById(R.id.spinner1);
final String[] groupes = new String[] {"A", "B", "C", "D", "E", "F", "G", "H"};
ArrayAdapter<CharSequence> featuresAdapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, new ArrayList<CharSequence>());
featuresAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(featuresAdapter);
for (String s : groupes) featuresAdapter.add(s);
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
// Here go your instructions when the user chose something
Toast.makeText(getBaseContext(), groupes[position], 0).show();
}
public void onNothingSelected(AdapterView<?> arg0) { }
});
It doesn't need any implementation in the class.
I have tried like the following. Take a button and give the click event to it. By changing the button background, it seems to be a spinner.
Declare as global variables alertdialog and default value..
AlertDialog d;
static int default_value = 0;
final Button btn = (Button) findViewById(R.id.button1);
btn .setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
//c.show();
final CharSequence str[] = {"Android","Black Berry","Iphone"};
AlertDialog.Builder builder =
new AlertDialog.Builder(TestGalleryActivity.this).setSingleChoiceItems(
str, default_value,new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int position)
{
Toast.makeText(TestGalleryActivity.this,
"" + position,
Toast.LENGTH_SHORT).show();
default_value = position;
btn.setText(str[position]);
if(d.isShowing())
d.dismiss();
}
}).setTitle("Select Any");
d = builder.create();
d.show();
}
});
Take a look at the iosched app for a general purpose solution to adding an element to the top of a list. In particular, if you are using a CursorAdapter, look at TracksAdapter.java which extends that definition to provide a "setHasAllItem" method and associated code to manage the list count to deal with the extra item at the top.
Using the custom adapter you can set the text to "Select One" or whatever else you may want that top item to say.
I found many good solutions for this. most is working by adding an item to the end of adapter, and don't display the last item in drop-down list.
The big problem for me was the spinner drop-down list will start from the bottom of the list. So user see the last items instead of the first items (in case of have many items to show), after touch the spinner for the first time.
So I put the hint item to the beginning of the list. and hide the first item in drop-down list.
private void loadSpinner(){
HintArrayAdapter hintAdapter = new HintArrayAdapter<String>(context, 0);
hintAdapter.add("Hint to be displayed");
hintAdapter.add("Item 1");
hintAdapter.add("Item 2");
.
.
hintAdapter.add("Item 30");
spinner1.setAdapter(hintAdapter);
//spinner1.setSelection(0); //display hint. Actually you can ignore it, because the default is already 0
//spinner1.setSelection(0, false); //use this if don't want to onItemClick called for the hint
spinner1.setOnItemSelectedListener(yourListener);
}
private class HintArrayAdapter<T> extends ArrayAdapter<T> {
Context mContext;
public HintArrayAdapter(Context context, int resource) {
super(context, resource);
this.mContext = context
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(android.R.layout.simple_spinner_item, parent, false);
TextView texview = (TextView) view.findViewById(android.R.id.text1);
if(position == 0) {
texview.setText("");
texview.setHint(getItem(position).toString()); //"Hint to be displayed"
} else {
texview.setText(getItem(position).toString());
}
return view;
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view;
if(position == 0){
view = inflater.inflate(R.layout.spinner_hint_list_item_layout, parent, false); // Hide first row
} else {
view = inflater.inflate(android.R.layout.simple_spinner_dropdown_item, parent, false);
TextView texview = (TextView) view.findViewById(android.R.id.text1);
texview.setText(getItem(position).toString());
}
return view;
}
}
set the below layout in #Override getDropDownView() when position is 0, to hide the first hint row.
R.layout.spinner_hint_list_item_layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</LinearLayout>
I think the easiest way is creating a dummy item on index 0 saying "select one" and then on saving maybe check that selection is not 0.
So this is my final example "all-in" for a button-spinner
In activity_my_form.xml
<Button
android:id="#+id/btnSpinnerPlanets"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="left|center_vertical"
android:singleLine="true"
android:text="#string/selectAPlanet"
android:textSize="10sp"
android:background="#android:drawable/btn_dropdown">
</Button>
In strings.xml
<string name="selectAPlanet">Select planet…</string>
<string-array name="planets__entries">
<item>The Sun with a name very long so long long long long longThe Sun with a name very long so long long long long longThe Sun with a name very long so long long long long long</item>
<item>Mercury</item>
<item>Venus</item>
<item>Earth</item>
<item>Mars</item>
<item>Jupiter</item>
<item>Saturn</item>
<item>Uranus</item>
<item>Neptune</item>
</string-array>
In MyFormActivity.java
public class MyFormActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
((Button) findViewById(R.id.btnSpinnerPlanets)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String[] items = view.getResources().getStringArray(R.array.planets__entries);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MyFormActivity.this, android.R.layout.simple_spinner_dropdown_item, items);
new AlertDialog.Builder(MyFormActivity.this).setTitle("the prompt").setAdapter(adapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((Button) findViewById(R.id.btnSpinnerPlanets)).setText(items[which]);
dialog.dismiss();
}
}).create().show();
}
});
}
}
Finally I obtained a font size configurable no first item selectable button spinner!!!
Thanks to HRJ
The best solution I found for this is actually not to use a Spinner but an AutoCompleteTextView. Its basically an EditText with attached Spinner to show suggestions as you type - but, with the right config, it can behave exactly as the OP wishes and more.
XML:
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/item"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.appcompat.widget.AppCompatAutoCompleteTextView
android:id="#+id/input"
android:hint="Select one"
style="#style/AutoCompleteTextViewDropDown"/>
</com.google.android.material.textfield.TextInputLayout>
Style:
<style name="AutoCompleteTextViewDropDown">
<item name="android:clickable">false</item>
<item name="android:cursorVisible">false</item>
<item name="android:focusable">false</item>
<item name="android:focusableInTouchMode">false</item>
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
</style>
As for the adapter use the basic ArrayAdapter or extend it to make your own, but no additional customization on the adapter side is necessary. Set the adapter on the AutoCompleteTextView.
When extending SpinnerAdapter, you override two View-producing methods, getView(int, View, ViewGroup) and getDropDownView(int, View, ViewGroup). The first one supplies the View inserted into the Spinner itself; the second supplies the View in the drop-down list (as the name suggests). You can override the getView(...) so that, until an item has been selected, it displays a TextView containing a prompt; then, when you detect an item has been selected, you change it to display a TextView corresponding to that.
public class PromptingAdapter extends SpinnerAdapter {
//... various code ...
private boolean selectionmade = false;
//call this method from the OnItemSelectedListener for your Spinner
public setSelectionState(boolean b) {
selectionmade = b;
}
#Override
public View getView(int position, View recycle, ViewGroup container) {
if(selectionmade) {
//your existing code to supply a View for the Spinner
//you could even put "return getDropDownView(position, recycle, container);"
}
else {
View output;
if(recycle instanceof TextView) {
output = recycle;
}
else {
output = new TextView();
//and layout stuff
}
output.setText(R.string.please_select_one);
//put a string "please_select_one" in res/values/strings.xml
return output;
}
}
//...
}
For those using Xamarin, here is the C# equivalent to aaronvargas's answer above.
using Android.Content;
using Android.Database;
using Android.Views;
using Android.Widget;
using Java.Lang;
namespace MyNamespace.Droid
{
public class NothingSelectedSpinnerAdapter : BaseAdapter, ISpinnerAdapter, IListAdapter
{
protected static readonly int EXTRA = 1;
protected ISpinnerAdapter adapter;
protected Context context;
protected int nothingSelectedLayout;
protected int nothingSelectedDropdownLayout;
protected LayoutInflater layoutInflater;
public NothingSelectedSpinnerAdapter(ISpinnerAdapter spinnerAdapter, int nothingSelectedLayout, Context context) : this(spinnerAdapter, nothingSelectedLayout, -1, context)
{
}
public NothingSelectedSpinnerAdapter(ISpinnerAdapter spinnerAdapter, int nothingSelectedLayout, int nothingSelectedDropdownLayout, Context context)
{
this.adapter = spinnerAdapter;
this.context = context;
this.nothingSelectedLayout = nothingSelectedLayout;
this.nothingSelectedDropdownLayout = nothingSelectedDropdownLayout;
layoutInflater = LayoutInflater.From(context);
}
protected View GetNothingSelectedView(ViewGroup parent)
{
return layoutInflater.Inflate(nothingSelectedLayout, parent, false);
}
protected View GetNothingSelectedDropdownView(ViewGroup parent)
{
return layoutInflater.Inflate(nothingSelectedDropdownLayout, parent, false);
}
public override Object GetItem(int position)
{
return position == 0 ? null : adapter.GetItem(position - EXTRA);
}
public override long GetItemId(int position)
{
return position >= EXTRA ? adapter.GetItemId(position - EXTRA) : position - EXTRA;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
// This provides the View for the Selected Item in the Spinner, not
// the dropdown (unless dropdownView is not set).
if (position == 0)
{
return GetNothingSelectedView(parent);
}
// Could re-use the convertView if possible.
return this.adapter.GetView(position - EXTRA, null, parent);
}
public override int Count
{
get
{
int count = this.adapter.Count;
return count == 0 ? 0 : count + EXTRA;
}
}
public override View GetDropDownView(int position, View convertView, ViewGroup parent)
{
// Android BUG! http://code.google.com/p/android/issues/detail?id=17128 -
// Spinner does not support multiple view types
if (position == 0)
{
return nothingSelectedDropdownLayout == -1 ?
new View(context) :
GetNothingSelectedDropdownView(parent);
}
// Could re-use the convertView if possible, use setTag...
return adapter.GetDropDownView(position - EXTRA, null, parent);
}
public override int GetItemViewType(int position)
{
return 0;
}
public override int ViewTypeCount => 1;
public override bool HasStableIds => this.adapter.HasStableIds;
public override bool IsEmpty => this.adapter.IsEmpty;
public override void RegisterDataSetObserver(DataSetObserver observer)
{
adapter.RegisterDataSetObserver(observer);
}
public override void UnregisterDataSetObserver(DataSetObserver observer)
{
adapter.UnregisterDataSetObserver(observer);
}
public override bool AreAllItemsEnabled()
{
return false;
}
public override bool IsEnabled(int position)
{
return position > 0;
}
}
}
I also solved this problem by using the following code. Suppose you are having a list of items e.g.
ArrayList<Item> itemsArrayList = new ArrayList<Item>();
Item item1 = new Item();
item1.setId(1);
item1.setData("First Element");
Item item2 = new Item();
item2.setId(2);
Item2.setData("Second Element");
itemsArrayList.add(item1);
itemsArrayList.add(item2);
Now we have to provide the strings to spinner because spinner can not understand the object. So we will create an new array list with string items like this ->
ArrayList<String> itemStringArrayList = new ArrayList<String>();
for(Item item : itemsArrayList) {
itemStringArrayList.add(item.getData());
}
Now we have itemStringArrayList array list with two string items. And we have to show the "Select Item" text as first item. So we have to insert an new string into the itemStringArrayList.
itemStringArrayList.add("Select Item");
Now we have an array list itemsArrayList and we want to show two elements in the drop down. But the condition here is ...If we don't select anything then Select Item should appear as first element which will not be enabled.
So we can implement this functionality like this. If you need to load the array list items into the android spinner. So you will have to use some adapter. So here i'll use the ArrayAdapter. We can use the customise adapter too.
ArrayAdapter<String> itemsArrayAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.spinner_item, itemsArrayList){
#Override
public boolean isEnabled(int position) {
if(position == 0)
{
return false;
}
else
{
return true;
}
}
#Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
View view = super.getDropDownView(position, convertView, parent);
TextView tv = (TextView) view;
if(position == 0){
// Set the hint text color gray
tv.setTextColor(Color.GRAY);
}
else {
tv.setTextColor(Color.BLACK);
}
return view;
}
};
itemsArrayAdapter.setDropDownViewResource(R.layout.spinner_item);
your_spinner_name.setAdapter(itemsArrayAdapter);
Here in this code. we are using the customised spinner layout i.e. R.layout.spinner_item. It's a simple text view
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textStyle="italic"
android:fontFamily="sans-serif-medium"
/>
We need to disable the first text in the spinner. So for the position 0 we are disabling the text. And color also we can set by overiding getDropDownView method. So in this way we will get the expected spinner.
I was facing the same problem yesterday and did not want to add a hidden item to the ArrayAdapter or use reflections, which works fine but is kind of dirty.
After reading many posts and trying around I found a solution by extending ArrayAdapter and Overriding the getView method.
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
/**
* A SpinnerAdapter which does not show the value of the initial selection initially,
* but an initialText.
* To use the spinner with initial selection instead call notifyDataSetChanged().
*/
public class SpinnerAdapterWithInitialText<T> extends ArrayAdapter<T> {
private Context context;
private int resource;
private boolean initialTextWasShown = false;
private String initialText = "Please select";
/**
* Constructor
*
* #param context The current context.
* #param resource The resource ID for a layout file containing a TextView to use when
* instantiating views.
* #param objects The objects to represent in the ListView.
*/
public SpinnerAdapterWithInitialText(#NonNull Context context, int resource, #NonNull T[] objects) {
super(context, resource, objects);
this.context = context;
this.resource = resource;
}
/**
* Returns whether the user has selected a spinner item, or if still the initial text is shown.
* #param spinner The spinner the SpinnerAdapterWithInitialText is assigned to.
* #return true if the user has selected a spinner item, false if not.
*/
public boolean selectionMade(Spinner spinner) {
return !((TextView)spinner.getSelectedView()).getText().toString().equals(initialText);
}
/**
* Returns a TextView with the initialText the first time getView is called.
* So the Spinner has an initialText which does not represent the selected item.
* To use the spinner with initial selection instead call notifyDataSetChanged(),
* after assigning the SpinnerAdapterWithInitialText.
*/
#Override
public View getView(int position, View recycle, ViewGroup container) {
if(initialTextWasShown) {
return super.getView(position, recycle, container);
} else {
initialTextWasShown = true;
LayoutInflater inflater = LayoutInflater.from(context);
final View view = inflater.inflate(resource, container, false);
((TextView) view).setText(initialText);
return view;
}
}
}
What Android does when initialising the Spinner, is calling getView for the selected item before calling getView for all items in T[] objects.
The SpinnerAdapterWithInitialText returns a TextView with the initialText, the first time it is called.
All the other times it calls super.getView which is the getView method of ArrayAdapter which is called if you are using the Spinner normally.
To find out whether the user has selected a spinner item, or if the spinner still displays the initialText, call selectionMade and hand over the spinner the adapter is assigned to.
See the answer with lightweight and high customisable library:
https://stackoverflow.com/a/73085435/6694920
<com.innowisegroup.hintedspinner.HintedSpinner
android:id="#+id/hintedSpinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="20dp"
app:hintTextSize="24sp"
app:hintTextColor="#color/red"
app:hint="Custom hint"
app:withDivider="true"
app:dividerColor="#color/dark_green"
app:arrowDrawable="#drawable/example_arrow_4"
app:arrowTint="#color/colorAccent"
app:popupBackground="#color/light_blue"
app:items="#array/text" />
Collapsed spinner:
Expanded spinner:
I'd just use a RadioGroup with RadioButtons if you only have three choices, you can make them all unchecked at first.
None of the previously submitted answers really worked the way I wanted to solve this issue. To me the ideal solution would provide the “Select One” (or whatever initial text) when the spinner is first displayed. When the user taps the spinner, the initial text shouldn’t be a part of the drop down that is displayed.
To further complicate my particular situation, my spinner data is coming form a cursor that is loaded via the LoaderManager callbacks.
After considerable experimentation I came up with the following solution:
public class MyFragment extends Fragment implements
LoaderManager.LoaderCallbacks<Cursor>{
private static final String SPINNER_INIT_VALUE = "Select A Widget";
private Spinner mSpinner;
private int mSpinnerPosition;
private boolean mSpinnerDropDownShowing = false;
private View mSpinnerDropDown;
private MyCursorAdapter mCursorAdapter;
...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
...
mCursorAdapter = new MyCursorAdapter(getActivity());
mSpinner = (Spinner) rootView.findViewById(R.id.theSpinner);
mSpinner.setOnTouchListener(mSpinnerTouchListener);
mSpinner.setAdapter(mCursorAdapter);
...
}
//Capture the touch events to toggle the spinner's dropdown visibility
private OnTouchListener mSpinnerTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if(mSpinnerDropDown != null && mSpinnerDropDownShowing == false){
mSpinnerDropDownShowing = true;
mSpinnerDropDown.setVisibility(View.VISIBLE);
}
return false;
}
};
//Capture the click event on the spinner drop down items
protected OnClickListener spinnerItemClick = new OnClickListener(){
#Override
public void onClick(View view) {
String widget = ((TextView) view.findViewById(android.R.id.text1)).getText().toString();
if(!widget.equals(SPINNER_INIT_VALUE)){
if(mCursorAdapter != null){
Cursor cursor = mCursorAdapter.getCursor();
if(cursor.moveToFirst()){
while(!cursor.isAfterLast()){
if(widget.equals(cursor.getString(WidgetQuery.WIDGET_NAME))){
...
//Set the spinner to the correct item
mSpinnerPosition = cursor.getPosition() + 1;
mSpinner.setSelection(mSpinnerPosition);
break;
}
cursor.moveToNext();
}
}
}
}
//Hide the drop down. Not the most elegent solution but it is the only way I could hide/dismiss the drop down
mSpinnerDropDown = view.getRootView();
mSpinnerDropDownShowing = false;
mSpinnerDropDown.setVisibility(View.GONE);
}
};
private class MyCursorAdapter extends CursorAdapter {
private final int DISPLACEMENT = 1;
private final int DEFAULT_ITEM_ID = Integer.MAX_VALUE;
private Activity mActivity;
public MyCursorAdapter(Activity activity) {
super(activity, null, false);
mActivity = activity;
}
//When loading the regular views, inject the defualt item
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(position == 0){
if(convertView == null){
convertView = mActivity.getLayoutInflater().inflate(R.layout.list_item_widget, parent, false);
}
return getDefaultItem(convertView);
}
return super.getView(position - DISPLACEMENT, convertView, parent);
}
//When loading the drop down views, set the onClickListener for each view
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent){
View view = super.getDropDownView(position, convertView, parent);
view.setOnClickListener(spinnerItemClick);
return view;
}
//The special default item that is being injected
private View getDefaultItem(View convertView){
TextView text = (TextView) convertView.findViewById(android.R.id.text1);
text.setText(SPINNER_INIT_VALUE);
return convertView;
}
#Override
public long getItemId(int position) {
if (position == 0) {
return DEFAULT_ITEM_ID;
}
return super.getItemId(position - DISPLACEMENT);
}
#Override
public boolean isEnabled(int position) {
return position == 0 ? true : super.isEnabled(position - DISPLACEMENT);
}
#Override
public int getViewTypeCount() {
return super.getViewTypeCount() + DISPLACEMENT;
}
#Override
public int getItemViewType(int position) {
if (position == 0) {
return super.getViewTypeCount();
}
return super.getItemViewType(position - DISPLACEMENT);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return mActivity.getLayoutInflater().inflate(R.layout.list_item_widget, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor){
if(cursor.isAfterLast()){
return;
}
TextView text = (TextView) view.findViewById(android.R.id.text1);
String WidgetName = cursor.getString(WidgetQuery.WIDGET_NAME);
text.setText(WidgetName);
}
}
}
I handle this by using a button instead of a Spinner. I have the sample project up on GitHub.
In the project, i'm displaying both the Spinner and button to show that they indeed look identical. Except the button you can set the initial text to whatever you want.
Here's what the activity looks like:
package com.stevebergamini.spinnerbutton;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Spinner;
public class MainActivity extends Activity {
Spinner spinner1;
Button button1;
AlertDialog ad;
String[] countries;
int selected = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner1 = (Spinner) findViewById(R.id.spinner1);
button1 = (Button) findViewById(R.id.button1);
countries = getResources().getStringArray(R.array.country_names);
// You can also use an adapter for the allert dialog if you'd like
// ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, countries);
ad = new AlertDialog.Builder(MainActivity.this).setSingleChoiceItems(countries, selected,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
button1.setText(countries[which]);
selected = which;
ad.dismiss();
}}).setTitle(R.string.select_country).create();
button1.setOnClickListener( new OnClickListener(){
#Override
public void onClick(View v) {
ad.getListView().setSelection(selected);
ad.show();
}});
}
}
NOTE: Yes, I realize that this is dependent on the applied Theme and the look will be slightly different if using Theme.Holo. However, if you're using one of the legacy themes such as Theme.Black, you're good to go.
Seems a banal solution but I usually put simply a TextView in the front of the spinner. The whole Xml looks like this. (hey guys, don't shoot me, I know that some of you don't like this kind of marriage):
<FrameLayout
android:id="#+id/selectTypesLinear"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<Spinner
android:id="#+id/spinnerExercises"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:entries="#array/exercise_spinner_entries"
android:prompt="#string/exercise_spinner_prompt"
/>
<TextView
android:id="#+id/spinnerSelectText"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Hey! Select this guy!"
android:gravity="center"
android:background="#FF000000" />
</FrameLayout>
Then I hide the TextView when an Item was selected. Obviously the background color of the TextView should be the same as the Spinner. Works on Android 4.0. Don't know on older versions.
Yes. Because the Spinner calls setOnItemSelectedListener at the beginning, the hiding of the textview could be a little bit tricky, but can be done this way:
Boolean controlTouched;
exerciseSpinner.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
controlTouched = true; // I touched it but but not yet selected an Item.
return false;
}
});
exerciseSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
if (controlTouched) { // Are you sure that I touched it with my fingers and not someone else ?
spinnerSelText.setVisibility(View.GONE);
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
for me it worked something like this. has the improvement that only changes the text in SOME options, not in all.
First i take the names of the spinner and create the arrayadapter with a customize view, but it doesn't matter now, the key is override the getView, and inside change the values u need to change. In my case was only the first one, the rest i leave the original
public void rellenarSpinnerCompeticiones(){
spinnerArrayCompeticiones = new ArrayList<String>();
for(Competicion c: ((Controlador)getApplication()).getCompeticiones()){
spinnerArrayCompeticiones.add(c.getNombre());
}
//ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this,R.layout.spinner_item_competicion,spinnerArrayCompeticiones);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, R.layout.spinner_item_competicion, spinnerArrayCompeticiones){
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View v = vi.inflate(R.layout.spinner_item_competicion, null);
final TextView t = (TextView)v.findViewById(R.id.tvCompeticion);
if(spinnerCompeticion.getSelectedItemPosition()>0){
t.setText(spinnerArrayCompeticiones.get(spinnerCompeticion.getSelectedItemPosition()));
}else{
t.setText("Competiciones");
}
return v;
}
};
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerCompeticion.setAdapter(spinnerArrayAdapter);
}
Refer to one of the above answers: https://stackoverflow.com/a/23005376/1312796
I added my code to fix a little bug. That where no data retrieved..How to show the prompt text..!
Here is my Trick...It works fine with me. !
Try to put your spinner in a Relative_layoutand align a Textview with your spinner and play with the visibility of the Textview (SHOW/HIDE) whenever the adapter of the spinner loaded or empty..Like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="20dp"
android:background="#ededed"
android:orientation="vertical">
<TextView
android:id="#+id/txt_prompt_from"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:textColor="#color/gray"
android:textSize="16sp"
android:layout_alignStart="#+id/sp_from"
android:text="From"
android:visibility="gone"/>
<Spinner
android:id="#+id/sp_from"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
/>
Here is the code:
txt__from = (TextView) rootView.findViewById(R.id.txt_prompt_from);
call this method after and before spinner adapter loaded and empty.
setPromptTextViewVisibility (); //True or fales
public void setPromptTextViewVisibility (boolean visible )
{
if (visible)
{
txt_from.setVisibility(View.VISIBLE);
}
else
{
txt_from.setVisibility(View.INVISIBLE);
}
}

Categories

Resources