简体   繁体   中英

Android Spinner fill with object

How can I fill a spinner with an Object.

Example: I have User object userId, userName, firstName, lastName. I need to fill display spinner with firstName. If user select I need to get userId.

    private void fillUserSpinner() {
            spinnerUserList = findViewById(R.id.spinnerUserList);
            ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this,
                    android.R.layout.simple_dropdown_item_1line, userDbHelp.gteUserIds());
            spinnerUserList.setAdapter(arrayAdapter);
        }


    private void onUserSelected() {
            spinnerUserList = findViewById(R.id.spinnerUserList);
            spinnerUserList.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
//Need to get selected userId
                }

                @Override
                public void onNothingSelected(AdapterView<?> adapterView) {

                }
            });
        }

You want display firstname alone, add this code into your model class:

@Override
public String toString() {
    return firstName;
}

use AppCompatSpinner together with an ArrayAdapter ... on case the items (POJO) of that ArrayAdapter override method toString() , one can skip manual assignment; that text is being displayed for the spinner's items then.

@Override
public String toString() {
    return this.firstName;
}

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