I am very new to android. I want to use 2 spinners in my application, one shows the countries list, when any country is selected the other spinner should show the list of ci
Here is a sample code which depicts the usage of spinner and action performed when spinner item is selected
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
public class MainActivity extends Activity {
Spinner spin;
String spin_val;
String[] gender = { "Male", "Female" };//array of strings used to populate the spinner
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);//setting layout
spin = (Spinner) findViewById(R.id.spinner_id);//fetching view's id
//Register a callback to be invoked when an item in this AdapterView has been selected
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView> arg0, View arg1,
int position, long id) {
// TODO Auto-generated method stub
spin_val = gender[position];//saving the value selected
}
@Override
public void onNothingSelected(AdapterView> arg0) {
// TODO Auto-generated method stub
}
});
//setting array adaptors to spinners
//ArrayAdapter is a BaseAdapter that is backed by an array of arbitrary objects
ArrayAdapter spin_adapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_spinner_item, gender);
// setting adapteers to spinners
spin.setAdapter(spin_adapter);
}
}
To add a list of values to the spinner, you then need to specify a SpinnerAdapter in your Activity, which extends Adapter class.. A spinner adapter allows to define two different views: one that shows the data in the spinner itself and one that shows the data in the drop down list when the spinner is pressed.You can also download & refer to the complete spinner_demo example project for better understanding.