I used setOnItemSelectedListener to specify which item is selected in a spinner, but i think it is not called. it should print "It works" when the program runs.
XML code:
<Spinner
android:id="@+id/quantity"
android:layout_width="94dp"
android:layout_height="27dp"
android:layout_x="11dp"
android:layout_y="118dp"
/>
Java code:
public class quantity extends Activity
{
Spinner quantity;
public void onCreate(Bundle savedInstanceState)
{
quantity=(Spinner)findViewById(R.id.quantity);
quantity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
{
Object item = parent.getItemAtPosition(pos);
System.out.println("it works... ");
}
public void onNothingSelected(AdapterView<?> parent)
{
}
});
}
}
Let the Spinner's first value be something like "-please select-". when the user clicks on the next button perform validation and check whether the value of the selectedItem in the spinner is "-please select-" and if yes, then display a toast and ask the the user to select something from the spinner.
Spinners provide a quick way to select one value from a set. In the default state, a spinner shows its currently selected value. Touching the spinner displays a dropdown menu with all other available values, from which the user can select a new one. You can add a spinner to your layout with the Spinner object.
This example demonstrates how do I get spinner value in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
Try this
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.Your_Layout);
//to fill your Spinner
List<String> spinnerArray = new ArrayList<String>();
spinnerArray.add("Item 1");
spinnerArray.add("Item 2");
spinnerArray.add("Item 3");
spinnerArray.add("Item 4");
spinnerArray.add("Item 5");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, spinnerArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner spinner = (Spinner) findViewById(R.id.quantity);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view,
int position, long id) {
Object item = adapterView.getItemAtPosition(position);
if (item != null) {
Toast.makeText(MainActivity.this, item.toString(),
Toast.LENGTH_SHORT).show();
}
Toast.makeText(MainActivity.this, "Selected",
Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
// TODO Auto-generated method stub
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With