简体   繁体   中英

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) {
    
    }
}

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM