Adding OnItemSelectedListener to Spinner

I have a button and a spinner (originally hidden). When the user presses the button, the counter is filled with elements and becomes visible. Now I would like to add OnItemSelectedListener to the spinner. and I tried a lot of textbooks with no luck.

This is my OnCreate feature.

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 setting does not work. The only way I got this is to configure my listener as routes.setOnItemSelectedListener(this) Then I implement OnItemSelectedListener and enable the necessary functions. But I have several spinners and you need to create separate listeners for different counters. Any help would be appreciated. Thanks!

+4
source share
2 answers

Declare your Spinner as a field, instantiate a listener as soon as you find findBeId, and use it wherever you want.

+1
source
  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 } }); 
+4
source

Source: https://habr.com/ru/post/1403289/


All Articles