首页 > 解决方案 > 使用 Spinner 打开另一个类

问题描述

尝试使用此代码从微调器的下拉列表中打开一个类。因此,如果按下帮助,则会打开帮助活动,如果按下导航,则会打开导航类

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

标签: javaandroid-studiodropdownspinneradapter

解决方案


由于您使用了 findViewById(...) ,我假设您在 Activity 中设置 onItemSelectedListener 。

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

推荐阅读