I have had a lot of difficulty with this as I have a custom spinner, if I setBackground then the Drawable would stretch. My solution to this was to add a drawable to the right of the Spinner TextView. Heres a code snippet from my Custom Spinner. The trick is to Override getView and customize the Textview as you wish.
public class NoTextSpinnerArrayAdapter extends ArrayAdapter<String> {
private String text = "0";
public NoTextSpinnerArrayAdapter(Context context, int textViewResourceId, List<String> objects) {
super(context, textViewResourceId, objects);
}
public void updateText(String text){
this.text = text;
notifyDataSetChanged();
}
public String getText(){
return text;
}
@NonNull
public View getView(int position, View convertView, @NonNull ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView textView = view.findViewById(android.R.id.text1);
textView.setCompoundDrawablePadding(16);
textView.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_menu_white_24dp, 0);
textView.setGravity(Gravity.END);
textView.setText(text);
return view;
}
}
You also need to set the Spinner background to transparent:
<lifeunlocked.valueinvestingcheatsheet.views.SelectAgainSpinner
android:id="@+id/saved_tickers_spinner"
android:background="@android:color/transparent"
android:layout_width="60dp"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="248dp"
tools:layout_editor_absoluteY="16dp" />
and my custom spinner if you want it....
public class SelectAgainSpinner extends android.support.v7.widget.AppCompatSpinner {
public SelectAgainSpinner(Context context) {
super(context);
}
public SelectAgainSpinner(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SelectAgainSpinner(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void setPopupBackgroundDrawable(Drawable background) {
super.setPopupBackgroundDrawable(background);
}
@Override
public void setSelection(int position, boolean animate) {
boolean sameSelected = position == getSelectedItemPosition();
super.setSelection(position, animate);
if (sameSelected) {
// Spinner does not call the OnItemSelectedListener if the same item is selected, so do it manually now
if (getOnItemSelectedListener() != null) {
getOnItemSelectedListener().onItemSelected(this, getSelectedView(), position, getSelectedItemId());
}
}
}
@Override
public void setSelection(int position) {
boolean sameSelected = position == getSelectedItemPosition();
super.setSelection(position);
if (sameSelected) {
// Spinner does not call the OnItemSelectedListener if the same item is selected, so do it manually now
if (getOnItemSelectedListener() != null) {
getOnItemSelectedListener().onItemSelected(this, getSelectedView(), position, getSelectedItemId());
}
}
}
}