Reputation: 575
how to put images icon on spinner in android please help me this is my spiner code how do i add images on every name in the list?? i want to show images on eact text on spinner
Spinner sp = (Spinner) findViewById(R.id.lgnspinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.network_array,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(adapter);
sp.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (position == 0) {
// text}
if (position == 1) {
// text
}
if (position == 2)
{
// text
}
if (position == 3) {
// text
}
}
}
});
XML:
<Spinner
android:id="@+id/lgnspinner"
style="?android:attr/buttonStyleSmall"
android:layout_width="145dip"
android:layout_height="wrap_content"
android:prompt="@string/network_prompt"
android:textColor="#000000" />
<string-array name="network_array" >
<item>
GPRS
</item>
<item>
Wifi
</item>
<item>
OtherNetwork
</item>
<item>
SMS
</item>
</string-array>
Upvotes: 0
Views: 10918
Reputation: 934
We will show how to add icons to an Android spinner using a SimpleCursorAdapter and a ViewBinder.
// get the spinner widget
mSpinner = (Spinner) findViewById(R.id.spinner1);
...
// fetch data from db. query might look something like this:
// SLECT _id, name FROM ....
mCursor = mDb.getData();
String[] from = new String[]{"_id", "name"};
int[] to = new int[]{R.id.icon, R.id.text};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.spinner_entry, mCursor, from, to);
adapter.setViewBinder(new SpinnerViewBinder());
mSpinner.setAdapter(adapter);
The layout spinner_entry.xml file for the spinner entry might look like this:
<!--?xml version="1.0" encoding="utf-8"?-->
<LinearLayout ...>
<ImageView android:id="@+id/icon" .../>
<TextView android:id="@+id/text" .../>
</LinearLayout>
The key lies in SpinnerViewBinder.java
public class SpinnerViewBinder implements SimpleCursorAdapter.ViewBinder {
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
int viewId = view.getId();
switch (viewId) {
case R.id.text:
// the textview
TextView mView = (TextView) view;
// display the name
mView.setText(cursor.getString(columnIndex));
break;
case R.id.icon:
// the icon
ImageView mIconView = (ImageView) view;
int dialectId = cursor.getInt(columnIndex);
switch (dialectId){
case 0:
mIconView.setImageResource(R.drawable.x1);
break;
case 1:
mIconView.setImageResource(R.drawable.x2);
break;
default:
mIconView.setImageResource(R.drawable.x3);
break;
}
}
return true;
}
}
For reference download this simple app: http://www.ziddu.com/download/12964268/AndroidCustomSpinner_files_101214a.zip.html
Upvotes: 7
Reputation: 591
See this : Customizing a spinner in android.
Hope it works for you.
Upvotes: 4