1) MainActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="spinnerimage.spinnerimage.MainActivity">
<Spinner
android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="88dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="@drawable/spinner"/>
</RelativeLayout>
2) MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<ItemData> list=new ArrayList<>();
list.add(new ItemData("Bank",R.drawable.bank_icon));
list.add(new ItemData("Entertainment",R.drawable.entertainment_icon));
list.add(new ItemData("Fashion",R.drawable.fashion_icon));
list.add(new ItemData("Govt",R.drawable.govt_icon));
Spinner sp=(Spinner)findViewById(R.id.spinner);
SpinnerAdapter adapter=new SpinnerAdapter(this,
R.layout.spinner_layout,R.id.txt,list);
sp.setAdapter(adapter);
}
}
3) ItemData.java
public class ItemData {
String text;
Integer imageId;
public ItemData(String text, Integer imageId){
this.text=text;
this.imageId=imageId;
}
public String getText(){
return text;
}
public Integer getImageId(){
return imageId;
}
}
4) SpinnerAdapter.java
public class SpinnerAdapter extends ArrayAdapter<ItemData> {
int groupid;
Activity context;
ArrayList<ItemData> list;
LayoutInflater inflater;
public SpinnerAdapter(Activity context, int groupid, int id, ArrayList<ItemData>
list){
super(context,id,list);
this.list=list;
inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.groupid=groupid;
}
public View getView(int position, View convertView, ViewGroup parent ){
View itemView=inflater.inflate(groupid,parent,false);
ImageView imageView=(ImageView)itemView.findViewById(R.id.img);
imageView.setImageResource(list.get(position).getImageId());
TextView textView=(TextView)itemView.findViewById(R.id.txt);
textView.setText(list.get(position).getText());
return itemView;
}
public View getDropDownView(int position, View convertView, ViewGroup
parent){
return getView(position,convertView,parent);
}
}