Adding OnItemSelectedListener to Spinner
Solution 1
Declare your Spinner as field instantiate the listener once you do findViewById and use it wherever you want.
Solution 2
final String[] s2 = getResources().getStringArray(R.array.capteur_size);
final EditText ed = (EditText) findViewById(R.id.editTextCoC);
spinnerCoC = (Spinner) findViewById(R.id.spinnerCoC);
spinnerCoC.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
ed.setText(s2[arg2]);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Quillion
I love programming. At this point programming for me is essential part of everyday life! It has become essential extension of me and regardless of what I do I can not be thinking about programming. And I love it!!! My kids ask me what programming is, and I say: Programming is like being a magician, you write a spell and it does magic.
Updated on July 14, 2022Comments
-
Quillion almost 2 years
I have a button and a spinner (originally hidden). When user presses a button, spinner gets populated with items and becomes visible. Now I would like to add OnItemSelectedListener to the spinner. and I have tried many tutorials with no luck.
This is my OnCreate function
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button load_routes = (Button)findViewById(R.id.load_routes); Spinner routes = (Spinner)findViewById(R.id.routes_list); load_routes.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { load_routes(v); } }); routes.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView<?> arg0, View v, int position, long id) { Log.v("routes", "route selected"); } public void onNothingSelected(AdapterView<?> arg0) { Log.v("routes", "nothing selected"); } }); }
This is my load_routes function
private void load_routes(View v) { Spinner routes = (Spinner)findViewById(R.id.routes_list); List<String> routes_list = RouteParser.get_routes(); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, routes_list); routes.setAdapter(adapter); TableRow list_of_routes_row = (TableRow)findViewById(R.id.list_of_routes_row); list_of_routes_row.setVisibility(View.VISIBLE); }
This set up does not work. The only way I got this to work is when I setup my listener as
routes.setOnItemSelectedListener(this)
Then I implementOnItemSelectedListener
and include the functions neccessary. But I have multiple spinners and need to create separate listeners for different spinner. Any help will be appreciated. Thanks!