I have created a Spinner and ArrayAdapter as follows:
Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
final ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(
this, R.array.units_array1, android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);
The units_array1 is a string array declared in a xml file like this:
<string-array name="units_array1">
<item>Centimeters</item>
<item>Meters</item>
<item>Kilometers</item>
<item>Inches</item>
<item>Foots</item>
<item>Miles</item>
</string-array>
Now I want to implement some If-ELSE conditions that are based on the elements in string-array. I Have researched a lot on the internet for this but haven't found out any solution that works. Please help me in implementing a function that returns the individual elements from the string-array using the adapter.
ArrayAdapter.getItem(position), where position is the index into the array. If you want to get the currently selected item in your Spinner, use Spinner.getSelectedItemPosition() as the parameter to getItem().
This will return a CharSequence because of you your adapter is typed. If you want that values to return as Strings, redefined your adapter as ArrayAdapter<String>
HTH!
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position, long id3) {
final String scale = adapter1.getItem(position);
// scale is gonna be "Centimeters" or "Meters", etc...
if (scale.equals("Centimeters")) {
// do something
} else if (scale.equals("Meters")) {
// do something else
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
ArrayAdapter has getItem(int position), which (if you know the position) will get you the String. ArrayAdapter also has getCount(), so you can write a simple for loop to get each element if you don't know its position.
You need to set a OnItemSelectedListener to your spinner. Then in the listener you'll be notified about the selection event. Check the official sample on this: Spinner.
Related
I have an android spinner that allows the user to select a translation. I can tap the spinner and it will reveal a list with available translations, but when I select an item in the list it will not appear in the spinner and neither does the onItemSelected method get called.
Here is the xml code for the spinner:
<Spinner
android:id="#+id/trans_list"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_toRightOf="#+id/chap_list"
android:layout_weight="1" />
Here is the relevant code for initiating the spinner. (edit) This code is ran from inside a Fragment class and not from my MainActivity class:
trans_spinner = v.findViewById(R.id.trans_list);
ArrayAdapter<String> adapter = new ArrayAdapter<>(v.getContext(), android.R.layout.simple_spinner_dropdown_item, translations);
trans_spinner.setAdapter(adapter);
trans_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String translation = trans_spinner.getItemAtPosition(trans_spinner.getSelectedItemPosition()).toString();
Log.d("trans", translation);
Toast.makeText(view.getContext(), translation, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Log.d("test", "1");
}
});
trans_spinner.setSelection(1);
Neither the onItemSelected() or onNothingSelected() method gets called when I select an item. I found this page describing an issue very similar to mine:
Android Spinner will not launch OnItemSelected and current selected item is not displayed in Spinner
However the user did not present a clear solution to their problem so it doesn't help me much.
I am not sure if it is relevant, but the items in the spinner are taken from an online webpage that provides JSON data to fill the spinner. This seems to work, as the options do appear in the spinner list. The issue is that upon selecting one of them, the spinner appears empty and the listener doesn't do anything.
So I found out that the issue was actually because of how I obtained the list of strings to put inside the spinner. As mentioned in the original post, I am loading the string values from a webpage in JSON format. I'm using the Retrofit2 API for this.
The problem was caused by the fact that I was downloading this data and then initializing the spinner both in the onCreateView() method of my fragment. What I did to fix it is I created a new method that initializes the spinner, and then I would call it from the onResponse() method used by the Retrofit API. This means that it doesn't initialize the spinner until after it has finished downloading/populating the list of strings.
<Spinner
android:id="#+id/planets_spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
f the available choices for your spinner are pre-determined, you can provide them with a string array defined in a string resource file:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="planets_array">
<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>
</resources>
With an array such as this one, you can use the following code in your Activity or Fragment to supply the spinner with the array using an instance of ArrayAdapter:
Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.planets_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
When the user selects an item from the drop-down, the Spinner object receives an on-item-selected event.
To define the selection event handler for a spinner, implement the AdapterView.OnItemSelectedListener interface and the corresponding onItemSelected() callback method. For example, here's an implementation of the interface in an Activity:
public class SpinnerActivity extends Activity implements OnItemSelectedListener {
...
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
}
The AdapterView.OnItemSelectedListener requires the onItemSelected() and onNothingSelected() callback methods.
Then you need to specify the interface implementation by calling setOnItemSelectedListener():
Spinner spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);
If you implement the AdapterView.OnItemSelectedListener interface with your Activity or Fragment (such as in the example above), you can pass this as the interface instance.
Java Code
public class MainActivity extends AppCompatActivity {
Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = findViewById(R.id.spinner);
List<String> translations = new ArrayList<>();
translations.add("string1");
translations.add("string2");
translations.add("string3");
translations.add("string4");
translations.add("string5");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, translations);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Object getPosition = parent.getItemAtPosition(position);
String value = getPosition.toString();
Toast.makeText(getActivity(), value, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
XML Code
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/spinner">
</Spinner>
Add this code after init adapter
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
And to get the selected item inside onItemSelected
translations.get(position)
I have one ListView and one Spinner. The Spinner is situated at the right top of the layout. My ListView contains some names (eg. country names) and the spinner has some alphabets (a-z). Suppose if I choose the letter "f" from the Spinner, my ListView must show the country names that starts only with the letter "f" . I want to sort my ListView by values from the Spinner?
You need to implement a Filter for your ListView. Everytime the OnItemSelectedListener of your Spinner gets called you need to filter the items. If you're not sure how to implement a filter in your ListView's adapter have a look at this: Filtering ListView with custom (object) adapter
I guess there won't be any way around implementing an own ListAdapter (it's easy).
Try to use the getFilter() method of the ListView adapter:
String[] filterL = { "a", "b", "c" }; //etc
//...
Spinner spin = (Spinner) findViewById(R.id.spinner1);
final ArrayAdapter<String> aspin = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, filterL); //the adapter for the Spinner
aspin.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(aspin);
final ArrayAdapter<String> aa = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, countries); //the adapter for the list
setListAdapter(aa); //set the adapter for the list(if you extend LisActivity) or call setAdapter on the ListView element
//add the listener:
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
boolean status = false;
public void onItemSelected(AdapterView<?> parent, View view,
int position, long arg3) {
if (!status) {
status = true;
return;
}
aa.getFilter().filter(filterL[position]);
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
I am trying to save spinner selected value, but i am getting like below i shown when i retrieve the details. Anybody know what is the problem.
Spinner:android.widget.Spinner#43e807a0
Have you used the getSelectedItem() inside setOnSelectedListner? If not, do as shown below:
mPres_doctor.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapter, View view,
int position, long id) {
String pres_doctor = mPres_doctor.getSelectedItem().toString();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
The result is displaying as an object value, usually I follow the below method to get the spinner values:
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.spinner, android.R.layout.spinner_layout);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
strings.xml
<string-array name="spinner">
<item>Dev</item>
<item>Stieve</item>
<item>John</item>
<item>Britto</item>
</string-array>
I have two spinners. Country and City.
I want to dynamically change the City's values upon Country selection.
I know how to create and initialize the values of Country but don't know how to set and change the City's values.
Any guidance is appreciated.
UPDATES1
The problem is, I don't have idea on how to update the content of City Spinner. I know listener and other basics on how to create a fixed spinner.
For the second spinner, use an Adapter over a List<String> (or whatever your City representation is). After changing the contents of the list, call notifyDataSetChanged on the adapter, and that will do.
You need to get a programmatic reference to the spinner, something like this:
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.setAdapter(adapter);
Then to update your city's values, use an OnItemSelectedListener, like this:
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
//update content of your city spinner using the value at index,
// id, or the view of the selected country.
}
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
Finally, you need to bind the listener to the country spinner like this:
spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
see here for reference: http://developer.android.com/resources/tutorials/views/hello-spinner.html
I need something like a combobox in access in android, i want to choose the customer per name, but in the background the id should be chosen. how to do?
In android comboboxes are called spinner. Nevertheless, gnugu has posted in his blog his own implementation of a combobox. http://www.gnugu.com/node/57
A simple example of an spinner would be the following.
First, edit your XML code with something like this
Spinner android:id="#+id/Spinner01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
Your java code should include something like this, the options are very intuitive. If you are using eclipse it will suggest you some options
public class SpinnerExample extends Activity {
private String array_spinner[];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Here come all the options that you wish to show depending on the
// size of the array.
array_spinner=new String[5];
array_spinner[0]="option 1";
array_spinner[1]="option 2";
array_spinner[2]="option 3";
array_spinner[3]="option 4";
array_spinner[4]="option 5";
Spinner s = (Spinner) findViewById(R.id.Spinner01);
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, array_spinner);
s.setAdapter(adapter);
}
}
An alternate solution to the need to link Customer ID to the selected Item.
To have a simple selector with text you cause make use of the array resources
Setup the Spinner in XML
<Spinner android:id="#+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/colors"/>
If you need more data linked with the spinner you can use Objects to populate the spinner.
The default functionality of an ArrayAdapter is to call toString() on any object and pass that to the view.
if (item instanceof CharSequence) {
text.setText((CharSequence)item);
} else {
text.setText(item.toString());
}
You can implement toString() in your object and it will display correctly in the spinner. Then to get the data back from the array you can add a handler onto ItemSelected and get the object back from the seed array or the ArrayAdapter.
ArrayAdapter adapter = new ArrayAdapter(activity, android.R.layout.simple_spinner_item, arrayOfObjects);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
Log.d(arrayOfObjects[position]._id);
}
});