Search code examples
javaandroid-studiodropdownspinneradapter

Use Spinner to open another class


Trying to use this code to open a class from a dropdown list on a spinner. So if help is pressed the help activity opens and if navigation is pressed the navigation class opens

//declare spinner.
        Spinner dropdown = findViewById(R.id.spinner1);
        String[] items = new String[]{"Help", "Navigation Help"};
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, items);

        dropdown.setAdapter(adapter);
        
    }

    public void onItemSelected(AdapterView<?> parent, View view,
                               int pos, long id) {
       
        
    }

    public void onNothingSelected(AdapterView<?> parent) {
    
    }
}

Solution

  • Since you have used findViewById(...) , I assume that you are setting onItemSelectedListener in an Activity.

    Context context = this;
    HashMap<String , Class> hashMap = new HashMap<>();
    hashMap.put("Naviagtion" , NavigationActivity.class);
    hashMap.put("Help" ,HelpActivity.class);
    
    public void onItemSelected(AdapterView<?> parent, View view,
                                   int pos, long id) {
           String string = adapter.getItem(pos);
           Intent intent = new Intent(context , hashMap.get(string));
           startActivity(intent);
    }