I am trying to populate a a spinner but I am getting an error with my String array saying "Array constants can only be used in initializers". My code works fine when i employ the string array as a local variable, but as a global variable it doesn't. I really need to be able to use my string array as a global variable. Thank you in advance. Here is my code:
deleteselection = (Spinner)view.findViewById(R.id.deletespinner);
ArrayAdapter<String> adapterdeletetype;
//createdenominationsarray = getResources().getStringArray(R.array.createdenominations); //<--works
//String [] createdenominationsarray = {"Select Portfolio", "Two", "Three"}; //<--works
createdenominationsarray = {"Select Portfolio", "Two", "Three"};// <--doesn'twork
adapterdeletetype = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,createdenominationsarray){
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent)
{
View v = null;
// If this is the initial dummy entry, make it hidden
if (position == 0) {
TextView tv = new TextView(getContext());
tv.setHeight(0);
tv.setVisibility(View.GONE);
v = tv;
}
else {
// Pass convertView as null to prevent reuse of special case views
v = super.getDropDownView(position, null, parent);
}
// Hide scroll bar because it appears sometimes unnecessarily, this does not prevent scrolling
parent.setVerticalScrollBarEnabled(false);
return v;
}
};
adapterdeletetype.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
denominationselection.setAdapter(adapterdeletetype);
I did the same thing for one of my project and it works for me. Below is the code snippet for your reference..
ArrayList<String> languages = new ArrayList<String>();
languages.add("English");
languages.add("German");
languages.add("French");
ArrayAdapter<String> langAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,languages);
ListView lv =(ListView)findViewById(R.id.listmain);
lv.setAdapter(langAdapter);
lv.setOnItemClickListener(new listclklisten(MainActivity.this));
public class listclklisten implements OnItemClickListener{
private Context parent;
public listclklisten(Context p){
parent=p;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TO DO your code here
}
}
inside string.xml Write:
<string-array name="spinner_array_environtment">
<item>Test</item>
<item>Production</item>
</string-array>
Inside your MainActivity.java :
public class MainActivity extends Activity {
Spinner spinner_environment;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner_environment = (Spinner) findViewById(R.id.spinnerview);
adapter =ArrayAdapter.createFromResource(this, R.array.spinner_array_environtment,R.layout.spinner_phone);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner_environment.setAdapter(adapter);
}
Inside spinner_phone.xml :
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/spinnerTarget"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="13dp"
android:textColor="#4C4646" />
try this out. Hope it will help you.
Related
I'm trying to change the color of each row, I have 2 arrays. One has names of color, the other has color codes.
I have a ListView with Color names, the names are stored in an array of String.
String[] colourNames;
String[] colourCodes;
protected void onCreate(Bundle savedInstanceState) {
colourNames = getResources().getStringArray(R.array.listArray);
colourCodes = getResources().getStringArray(R.array.listValues);
ListView lv = (ListView) findViewById(R.id.listView);
ArrayAdapter aa = new ArrayAdapter(this, R.layout.activity_listview, colourNames);
lv.setAdapter(aa);
for(int i=0; i<colourCodes.length; i++)
lv.getChildAt(i).setBackgroundColor(Color.parseColor(colourCodes[i]));
}
In arrays.xml:
<string-array name="listArray">
<item>aliceblue</item>
<item>antiquewhite</item>
<item>aquamarine</item>
<item>azure</item>
</string-array>
<string-array name="listValues">
<item>00f0f8ff</item>
<item>00faebd7</item>
<item>007fffd4</item>
<item>00f0ffff</item>
</string-array>
The app crashes at lv.getChildAt(i).setBackgroundColor(Color.parseColor(colourCodes[i]));
You must write your own custom ArrayAdapter.
First write a color class:
color.java:
public class color {
private String name;
private String color;
public color(String name, String color) {
this.name = name;
this.color = color;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
Then List item layout:
list_item_layout.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Finally write custom adapter:
ColorListAdapter.java:
public class ColorListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private List<color> mColorList;
public ColorListAdapter(Activity activity, List<color> mColorList) {
mInflater = (LayoutInflater) activity.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
this.mColorList = mColorList;
}
#Override
public int getCount() {
return mColorList.size();
}
#Override
public Object getItem(int position) {
return mColorList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView;
// Get item_layout:
rowView = mInflater.inflate(R.layout.list_item_layout, null);
// Get TextView from item_layout:
TextView textView =
(TextView) rowView.findViewById(R.id.name);
// Get color and text from current position set TextView
color myColor = mColorList.get(position);
textView.setText(myColor.getName());
textView.setBackgroundColor(Color.parseColor(myColor.getColor()));
return rowView;
}
}
And these are MainActivity.java and activity_main.xml
MainActivity.java:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<color> colorList = new ArrayList<>();
// Add color objects:
colorList.add(new color("RED", "#FF0000"));
colorList.add(new color("GREEN", "#00FF00"));
colorList.add(new color("BLUE", "#0000FF"));
colorList.add(new color("MY BEST", "#013583"));
// Add list to your custom adapter
ListView myListView = (ListView) findViewById(R.id.liste);
ColorListAdapter mAdapter = new ColorListAdapter(this, colorList);
// Set Adapter
myListView.setAdapter(mAdapter);
}
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/liste"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</RelativeLayout>
Try this code
String[] colourNames;
String[] colourCodes;
protected void onCreate(Bundle savedInstanceState) {
colourNames = getResources().getStringArray(R.array.listArray);
colourCodes = getResources().getStringArray(R.array.listValues);
ListView lv = (ListView) findViewById(R.id.listView);
ArrayAdapter aa = new ArrayAdapter(this, R.layout.activity_listview, colourNames);
lv.setAdapter(aa);
for(int i=0; i<colourCodes.length; i++){
View wantedView = lv.getChildAt(i);
view.setBackgroundColor(Color.BLUE);
}
}
The problem is at this point ListView does not have any children. If you want to alter how children are displayed, you need create your own Adapter implementation and override getView(). You can simply subclass ArrayAdapter in this case and pass it your array of colors (or have it load the colors in the adapter, as I have done), then choose a color based on position.
Also, you might as well make your colors an integer array.
<integer-array name="listValues">
<item>0xfff0f8ff</item>
<item>0xfffaebd7</item>
<item>0xff7fffd4</item>
<item>0xfff0ffff</item>
</integer-array>
public class ColorsAdapter extends ArrayAdapter<String> {
private int[] mColors;
public ColorsAdapter(Context context) {
super(context, R.layout.activity_listview,
context.getResources().getStringArray(R.array.listArray));
mColors = context.getResources().getIntegerArray(R.array.listValues);
{
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
int color = mColors[position % mColors.length]; // might as well be safe
view.setBackgroundColor(color);
return view;
}
}
I also highly recommend watching this video on how ListView works: The World of ListView. Also, nowadays people are moving toward RecyclerView instead; you don't have to do that necessarily, but either way this video should help you understand how these components behave.
I've been trying to make listView redirect user onClick to URL's when clicking on different elements.
Example:
clicking on "apple" would open "stackoverflow.com",
but clicking on tomato would open "google.com" etc.
Could anyone give me some advice how can I accomplish this, because after 2 days of trying and searching all I've got is a headache..
displayMainMenu.java
public class DisplayMainMenu extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_main_menu);
final String[] food = new String[] {"Apple", "Tomato", "Potato"};
ListAdapter adapter = new MyAdapter(this, food);
ListView listView = (ListView) findViewById(R.id.mainMenu);
listView.setAdapter(adapter);
}
class MyAdapter extends ArrayAdapter<String>
{
public MyAdapter(Context context, String[] values)
{
super(context, R.layout.entry, values);
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = LayoutInflater.from(getContext());
View view = inflater.inflate(R.layout.entry, parent, false);
String text = getItem(position);
TextView textView = (TextView) view.findViewById(R.id.listTextView1);
textView.setText(text);
return view;
}
}
}
You should make a new class that holds the shown string value (Apple, Tomato, Potato, etc) and also holds the URL that you want to link to.
Then make the ArrayAdapter use that class. The getView function you have already should suffice (when its updated to use the new class).
Then in your activity, use 'setOnItemClickListener' to set a new listener.
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MyItem clickedItem = () parent.getItemAtPosition(position);
<< Insert code to open the link with the URL you can get from 'clickedItem' >>
}
});
That should do it.
I have implementing a tutorial and I have a problem to adapt to my way.
The main.xml with de ListView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<ListView android:id="#+id/listView1" android:layout_height="match_parent" android:layout_width="match_parent" />
</LinearLayout>
The rowview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="wrap_content" android:weightSum="1">
<TextView android:layout_width="wrap_content"
android:layout_height="match_parent" android:id="#+id/text"
android:layout_weight="0.5" android:textSize="25sp" />
<Spinner android:layout_width="0dp" android:layout_height="wrap_content"
android:id="#+id/spin" android:prompt="#string/choice_prompt"
android:layout_weight="0.5" />
</LinearLayout>
The strings.xml file.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, ListViewTestActivity!</string>
<string name="app_name">ListViewTest</string>
<string name="choice_prompt">Select a choice</string>
<string-array name="choices">
<item>Alpha</item>
<item>Bravo</item>
<item>Charlie</item>
</string-array>
</resources>
The ListViewActivity class:
public class ListViewTestActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView listView = (ListView) findViewById(R.id.listView1);
DataHolder data = new DataHolder(this);
DataHolder data1 = new DataHolder(this);
DataHolder data2 = new DataHolder(this);
DataHolder data3 = new DataHolder(this);
DataHolder data4 = new DataHolder(this);
DataAdapter d = new DataAdapter(this, R.layout.rowview, new DataHolder[] { data, data1, data2, data3, data4 });
listView.setAdapter(d);
}
}
The DataHolder class:
public class DataHolder {
private int selected;
private ArrayAdapter<CharSequence> adapter;
public DataHolder(Context parent) {
adapter = ArrayAdapter.createFromResource(parent, R.array.choices, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}
public ArrayAdapter<CharSequence> getAdapter() {
return adapter;
}
public String getText() {
return (String) adapter.getItem(selected);
}
public int getSelected() {
return selected;
}
public void setSelected(int selected) {
this.selected = selected;
}
}
All the DataHolder class :
public class DataAdapter extends ArrayAdapter<DataHolder> {
private Activity myContext;
public DataAdapter(Activity context, int textViewResourceId, DataHolder[] objects) {
super(context, textViewResourceId, objects);
myContext = context;
}
// We keep this ViewHolder object to save time. It's quicker than findViewById() when repainting.
static class ViewHolder {
protected DataHolder data;
protected TextView text;
protected Spinner spin;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
// Check to see if this row has already been painted once.
if (convertView == null) {
// If it hasn't, set up everything:
LayoutInflater inflator = myContext.getLayoutInflater();
view = inflator.inflate(R.layout.rowview, null);
// Make a new ViewHolder for this row, and modify its data and spinner:
final ViewHolder viewHolder = new ViewHolder();
viewHolder.text = (TextView) view.findViewById(R.id.text);
viewHolder.data = new DataHolder(myContext);
viewHolder.spin = (Spinner) view.findViewById(R.id.spin);
viewHolder.spin.setAdapter(viewHolder.data.getAdapter());
// Used to handle events when the user changes the Spinner selection:
viewHolder.spin.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
viewHolder.data.setSelected(arg2);
viewHolder.text.setText(viewHolder.data.getText());
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
// Update the TextView to reflect what's in the Spinner
viewHolder.text.setText(viewHolder.data.getText());
view.setTag(viewHolder);
Log.d("DBGINF", viewHolder.text.getText() + "");
} else {
view = convertView;
}
// This is what gets called every time the ListView refreshes
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(getItem(position).getText());
holder.spin.setSelection(getItem(position).getSelected());
return view;
}
}
To see the result of this code, see -> Android Listview with spinner and a checkbox
This code works, I have a listView with a spinner for each item, but how I can fill spinners with my own Strings? I tryed to fill them in the DataHolder class but it fails. (I have a list of Strings).
Thank's in advance.
All the work is done in the ADAPTER here your DataAdapter.
The cells are constructed in the method GetView, each cells is recycled : if convertView is null you create a new cell to use or else you use convertView.
i assume you must change some code in your DataHolder
public DataHolder(Context parent) {
adapter = ArrayAdapter.createFromResource(parent, R.array.choices, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}
For now you must understand that the array of choices is provided statically :
R.array.choices
One solution would be to pass your data when constructing the viewHolders here :
viewHolder.data = new DataHolder(myContext);
should looks like something like this :
viewHolder.data = new DataHolder(myContext, myDataArray);
and then in your class change the instanciation of the adapter with something more like that..
public DataHolder(Context parent, ArrayList<String> dataArray) {
adapter = new ArrayAdapter<String>(myContext, yourTextViewId, dataArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}
hopes it help
good luck
I have created a Spinner that is populated with an ArrayList. I want to dynamically add values to the ArrayList, so the the Spinner populates dynamically. However, when I try to add values to my ArrayList, I get a NullPointerException.
What am I missing? Do I have to reset the adapter before amending the ArrayList?
Here is my code:
My spinner, arraylist, and adapter:
deleteselection = (Spinner)view.findViewById(R.id.deletespinner);
portfoliosdelete = new ArrayList<String>();
portfoliosdelete.add("Select Portfolio");
adapterdeletetype = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,portfoliosdelete){
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent)
{
View v = null;
// If this is the initial dummy entry, make it hidden
if (position == 0) {
TextView tv = new TextView(getContext());
tv.setHeight(0);
tv.setVisibility(View.GONE);
v = tv;
}
else {
// Pass convertView as null to prevent reuse of special case views
v = super.getDropDownView(position, null, parent);
}
// Hide scroll bar because it appears sometimes unnecessarily, this does not prevent scrolling
parent.setVerticalScrollBarEnabled(false);
return v;
}
};
adapterdeletetype.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
deleteselection.setAdapter(adapterdeletetype);
My code to dynamically update spinner:
else if(users.contains(usernull)){
pn1 = enterportfolioname.getText().toString();
user1 = new PortfolioRecord(pn1, "someemail#gmail.com");
users.remove(usernull);
users.add(user1);
portfoliosdelete.add(pn1); // <-- This causes a null pointer exception
adapterdeletetype.notifyDataSetChanged();
portfoliolist.invalidateViews();
Use the code below. This code will add a new item when the user selects and add a new item from the spinner.
Code sample:
layout main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:weightSum="10" >
<Spinner
android:id="#+id/cmbNames"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
layout spinner_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Activity class:
public class MainActivity extends Activity {
private static final String NAME = "name";
private static final String ADD_NEW_ITEM = "Add New Item";
private SimpleAdapter adapter;
private Spinner cmbNames;
private List<HashMap<String, String>> lstNames;
private int counter;
private OnItemSelectedListener itemSelectedListener = new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
HashMap<String, String> map = lstNames.get(arg2);
String name = map.get(NAME);
if (name.equalsIgnoreCase(ADD_NEW_ITEM)) {
lstNames.remove(map);
counter++;
addNewName(String.valueOf(counter));
addNewName(ADD_NEW_ITEM);
adapter.notifyDataSetChanged();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
populateList();
cmbNames = (Spinner) findViewById(R.id.cmbNames);
adapter = new SimpleAdapter(this, lstNames, R.layout.spinner_item,
new String[] { NAME }, new int[] { R.id.tvName });
cmbNames.setAdapter(adapter);
cmbNames.setOnItemSelectedListener(itemSelectedListener);
}
private void populateList() {
lstNames = new ArrayList<HashMap<String, String>>();
addNewName("abc");
addNewName("pqr");
addNewName("xyz");
addNewName(ADD_NEW_ITEM);
}
private void addNewName(String name) {
HashMap<String, String> map = new HashMap<String, String>();
map.put(NAME, name);
lstNames.add(map);
}
}
Try to call delete on adapterdeletetype instead of the arraylist. If it fails, then please post your logcat output.
I have a array list like this:
private ArrayList<Locations> Artist_Result = new ArrayList<Location>();
This Location class has two properties: id and location.
I need to bind my ArrayList to a spinner. I have tried it this way:
Spinner s = (Spinner) findViewById(R.id.SpinnerSpcial);
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, Artist_Result);
s.setAdapter(adapter);
However, it shows the object's hexadecimal value. So I think I have to set display the text and value for that spinner controller.
The ArrayAdapter tries to display your Location-objects as strings (which causes the Hex-values), by calling the Object.toString()-method. It's default implementation returns:
[...] a string consisting of the name of the class of which the object
is an instance, the at-sign character `#', and the unsigned
hexadecimal representation of the hash code of the object.
To make the ArrayAdadpter show something actually useful in the item list, you can override the toString()-method to return something meaningful:
#Override
public String toString(){
return "Something meaningful here...";
}
Another way to do this is, to extend BaseAdapter and implement SpinnerAdapter to create your own Adapter, which knows that the elements in your ArrayList are objects and how to use the properties of those objects.
[Revised] Implementation Example
I was playing around a bit and I managed to get something to work:
public class Main extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create and display a Spinner:
Spinner s = new Spinner(this);
AbsListView.LayoutParams params = new AbsListView.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT
);
this.setContentView(s, params);
// fill the ArrayList:
List<Guy> guys = new ArrayList<Guy>();
guys.add(new Guy("Lukas", 18));
guys.add(new Guy("Steve", 20));
guys.add(new Guy("Forest", 50));
MyAdapter adapter = new MyAdapter(guys);
// apply the Adapter:
s.setAdapter(adapter);
// onClickListener:
s.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
/**
* Called when a new item was selected (in the Spinner)
*/
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
Guy g = (Guy) parent.getItemAtPosition(pos);
Toast.makeText(
getApplicationContext(),
g.getName()+" is "+g.getAge()+" years old.",
Toast.LENGTH_LONG
).show();
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
});
}
/**
* This is your own Adapter implementation which displays
* the ArrayList of "Guy"-Objects.
*/
private class MyAdapter extends BaseAdapter implements SpinnerAdapter {
/**
* The internal data (the ArrayList with the Objects).
*/
private final List<Guy> data;
public MyAdapter(List<Guy> data){
this.data = data;
}
/**
* Returns the Size of the ArrayList
*/
#Override
public int getCount() {
return data.size();
}
/**
* Returns one Element of the ArrayList
* at the specified position.
*/
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int i) {
return i;
}
/**
* Returns the View that is shown when a element was
* selected.
*/
#Override
public View getView(int position, View recycle, ViewGroup parent) {
TextView text;
if (recycle != null){
// Re-use the recycled view here!
text = (TextView) recycle;
} else {
// No recycled view, inflate the "original" from the platform:
text = (TextView) getLayoutInflater().inflate(
android.R.layout.simple_dropdown_item_1line, parent, false
);
}
text.setTextColor(Color.BLACK);
text.setText(data.get(position).name);
return text;
}
}
/**
* A simple class which holds some information-fields
* about some Guys.
*/
private class Guy{
private final String name;
private final int age;
public Guy(String name, int age){
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
}
I fully commented the code, if you have any questions, don't hesitate to ask them.
Simplest Solution
After scouring different solutions on SO, I found the following to be the simplest and cleanest solution for populating a Spinner with custom Objects. Here's the full implementation:
Location.java
public class Location{
public int id;
public String location;
#Override
public String toString() {
return this.location; // What to display in the Spinner list.
}
}
res/layout/spinner.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="14sp"
android:textColor="#FFFFFF"
android:spinnerMode="dialog" />
res/layout/your_activity_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<Spinner
android:id="#+id/location" />
</LinearLayout>
In Your Activity
// In this case, it's a List of Locations, but it can be a List of anything.
List<Location> locations = Location.all();
ArrayAdapter locationAdapter = new ArrayAdapter(this, R.layout.spinner, locations);
Spinner locationSpinner = (Spinner) findViewById(R.id.location);
locationSpinner.setAdapter(locationAdapter);
// And to get the actual Location object that was selected, you can do this.
Location location = (Location) ( (Spinner) findViewById(R.id.location) ).getSelectedItem();
Thanks to Lukas' answer above (below?) I was able to get started on this, but my problem was that his implementation of the getDropDownView made the dropdown items just a plain text - so no padding and no nice green radio button like you get when using the android.R.layout.simple_spinner_dropdown_item.
So as above, except the getDropDownView method would be:
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent)
{
if (convertView == null)
{
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(android.R.layout.simple_spinner_dropdown_item, null);
}
TextView textView = (TextView) convertView.findViewById(android.R.id.text1);
textView.setText(items.get(position).getName());
return convertView;
}
Well, am not gonna confuse with more details.
Just create your ArrayList and bind your values like this.
ArrayList tExp = new ArrayList();
for(int i=1;i<=50;i++)
{
tExp.add(i);
}
Assuming that you have already a spinner control on your layout say with id, spinner1. Add this code below.
Spinner sp = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adp1=new ArrayAdapter<String>this,android.R.layout.simple_list_item_1,tExp);
adp1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(adp1);
All the above code goes under your onCreate function.
Thank Lukas, you help me a lot.
I d'like to improve your answer.
If you just want to access the selected item later, you can use this :
Spinner spn = (Spinner) this.findViewById(R.id.spinner);
Guy oGuy = (Guy) spn.getSelectedItem();
So you don't have to use the setOnItemSelectedListener() in your initialisation :)