I have a little problem with a spinner.
I create a Spinner the user click a Button. The Spinner is shown as it should be, but when onItemSelected should be called nothing happens.
Here is the code
public void setUpSpinner(){
spinner = new Spinner(this);
CustomArrayAdapter<String> adapter = new CustomArrayAdapter<String>(this, android.R.layout.simple_spinner_item, getAsStrings());
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
}
public void onClick(View view) {
spinner.performClick();
}
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String getName = (String) spinner.getSelectedItem();
getListFromName(getName);
}
Anyone knows what is wrong here?
Thank you guys.
Solved the problem by adding a Spinner in my xml with height and width set to zero.
This looks enough like the turorial, so refer back to that. See below:
I don't see this, but does the main class implement OnItemSelectedListener? Also, You'll want to instantiate the Spinner inside the onCreate() within the main class body.
This line needs to be within the onCreate();
spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
why do you have spinner = new Spinner(this) in the set-up ?
surely you already have a Spinner in the XML of your layout, then you simply do spinner = (Spinner) findViewById(R.id.WHATEVER_THE_ID_IS_IN_THE_XML); so you don't need a new
P.S. this is how I define a Spinner in an XML layout
<Spinner
android:id="#+id/SPINNER_ID"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:gravity="center_horizontal" />
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 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 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);
}
});
I have a spinner with a background image. But when I add array adapter to the spinner, the text is shown on the background image. I want to hide this text. There is also a TextView. My requirement is, when I click the image, the spinner should pop up and when I selects an item, the TextView gets updated with the selected item.
Spinner spin = (Spinner) d.findViewById(R.id.searchCriteria);
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// hide selection text
((TextView)view).setText(null);
// if you want you can change background here
}
public void onNothingSelected(AdapterView<?> arg0) {}
});
Create ghost_text.xml in your layouts folder with this text:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/transparent" />
Then use that file in your adapter like this:
ArrayAdapter<String> your_adapter = new ArrayAdapter<String>(this,
R.layout.ghost_text, your_list);
your_spinner.setAdapter(your_adapter);
You should also be able to use this technique with other resource-based adapters.
Probably you can define a xml-layout file, without any textview in it, and supply it to the adapter for the spinner.
e.g. empty_spinner_item.xml
<ImageView xmlns:android="http..."
android:layout_width=".."
/>
and then use any adapter:
spinner.setAdapter(new SimpleAdapter(this, data, R.layout.empty_spinner_item, ... ));