Android create a spinner with items that have a hidden value and display some text?

后端 未结 5 1534
既然无缘
既然无缘 2020-12-10 11:06

I\'m sure this is asked plenty and i\'ve found some questions on here similar but none really got the coin dropping for me. I\'m hoping someone can help me out.

What

5条回答
  •  一向
    一向 (楼主)
    2020-12-10 11:47

    You can instantiate an ArrayAdapter typed with you data object type. The Spinner will then hold your complete data object instead of a String. Values displayed will be determined by the toString() method of your data objects.

    Example:

    List allProjects = ...;
    
        ArrayAdapter spinnerAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item,allProjects.toArray(new Project[allProjects.size()]));
        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(spinnerAdapter);
        spinner.setOnItemSelectedListener(this);
    

    ...

    @Override
    public void onItemSelected(AdapterView parent, View view, int position, long id) {
        Log.i(AppConst.TAG, "ItemSelected:" + position + " id: " + id);
        Project selectedProject = (Project)getSpinner().getSelectedItem();
        currentTask = selectedProject.toString();
        Log.i(AppConst.TAG, "Selected Project:" + selectedProject.getId());
        ...
    }
    

提交回复
热议问题