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
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 four Spinner ,First spinner display data when user select on spinner item data then other spinner data is displayed .First time,i have loaded all data in spinner when user select first spinner then data should be changed to refresh to second Spinner
How data is changed in second spinner
First you would need to get a reference of your spinner like -
Spinner mySpinner = (Spinner) findViewById(R.id.mySpinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.myArray, android.R.layout.mySpinnerItem);
adapter.setDropDownViewResource(android.R.layout.myDropdownItem);
spinner.setAdapter(adapter);
To change the values you would do -
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
//change content
}
}
public void onNothingSelected(AdapterView parent) {
//do nothing
}
}
Set a listener on the setOnItemSelectedListener of your first Spinner, with the appropriate code to populate your second Spinner. This way when you change the value of the first Spinner, the second Spinner will be updated.
I am dynamically adding the Spinners in my application by parsing the XML file.
I have done using the below code
List<Spinner> allspin = new ArrayList<Spinner>();
Spinner spin = new Spinner(getParent());
allspin.add(spin);
spin.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getParent(),
android.R.layout.simple_spinner_item, selectval);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(adapter);
Spinners are displayed correctly but i don't know how to retrieve the value of selected spinner. If there is one spinner i can retieve, but there are multiple how should i do?
You can get the reference of the spinner from your arraylist like this :
Spinner spn = allspin.get(index);
After that you can get the selected item by simply calling:
spn.getSelectedItemPosition();
You can set id of spinner dynamically.
For that,you can use
spin.setId(i); //if you use i of for loop for creating multipal spin at a tym or you can use a global variable i,incremented by one each time you create a spinner
and further,you can use those ids to get values from particular spinner.
Example:
for(int i=1;i<4;i++)
{
Spinner spin=new Spinner(getApplicationCotext());
spin.setId(i);
...
//other code
...
mLayout.add(spin);//add this spinner to your layout(mLayout is object of your layout in xml)
}
Now,
for(int i=1;i<4;i++)
{
Spinner sp=(Spinner)findViewById(i);
sp.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
System.out.println(sp.getText().toString());//prints values of a pinner when it is changed/selected
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
If you need multiple spinners (I'm not sure I understand your use case), then, as you're creating each of them, you need to also create the appropriate listeners. You shouldn't have to retrieve values of spinners yourself; handling these selection events should be done in your listeners. Perhaps if you explained what you're attempting to do a bit better it would be easier to help...
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.
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);
}
});