Many a times we find that it becomes quite hard to work with some simplest looking stuffs, and then we try to find out the hardest possible ways for working with them.
I wont say its easiest but yeah its quite handy for people who wanna show dynamic data in a Spinner widget in Android.
Assumptions:
1. You are using ArrayList<DataType> dynamicData;
2. You have overriden toString function in your data class which holds the dynamic data.
class DataType{
String spinnerElement;
@Override
public String toString(){
return spinnerElement;
}
}
3. You know Android development :D
///////////////////////////////////////////////////////////////////////IMPLEMENTATION///////////////////////////////////////////////
Object[] items = dynamicData.toArray();
String[] elements= new String[items.length + 1];
for (int iTemp = 0; iTemp < items.length + 1; iTemp++) {
if (i == 0) {
elements[i] = "Please select";
} else {
elements[i] = ((DataType) items[i - 1]).toString();
}
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_spinner_item, prices);
// you can also use the default android.R.layout.single_line_spinner
// In order to support multi-line selection i have modified the source of default.
arrayAdapter .setDropDownViewResource(R.layout.single_line_spinner);
((Spinner) findViewById(R.id.mySpinner)).setAdapter(arrayAdapter );
//////////////////////////////////////////////////////////////////////////THATS IT /////////////////////////////////////////////////////////////////
R.layout.single_line_spinner
/**
Do not modify this source as the spinner uses this id only
*/
<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
style="?android:attr/spinnerDropDownItemStyle"
android:singleLine="false"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:ellipsize="marquee" />
Let me know what you think about it or if have any better idea for the same.
No comments:
Post a Comment