Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Spinner Custom Object Example
import android.os.Bundle;
import android.support.v4.util.ArrayMap;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
public class MainActivity extends AppCompatActivity {
private final static String TAG = MainActivity.class.getName();
private final String[] keys = {
"Object 1",
"Object 2",
"Object 3"
};
private final CustomObject[] objects = {
new CustomObject("Object 1", 1),
new CustomObject("Object 2", 2),
new CustomObject("Object 3", 3)
};
private final ArrayMap<String, Integer> map = new ArrayMap<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner spinner1 = findViewById(R.id.spinner1);
Spinner spinner2 = findViewById(R.id.spinner2);
for (CustomObject object : objects) {
map.put(object.text, object.id);
}
ArrayAdapter<String> adapter1 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, keys);
spinner1.setAdapter(adapter1);
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
String key = (String) adapterView.getItemAtPosition(pos);
int id = map.get(key);
Log.i(TAG, "Spinner1: id is " + id);
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
ArrayAdapter<CustomObject> adapter2 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, objects);
spinner2.setAdapter(adapter2);
spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
CustomObject object = (CustomObject) adapterView.getItemAtPosition(pos);
Log.i(TAG, "Spinner2 : id is " + object.id);
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment