Skip to content

Instantly share code, notes, and snippets.

@nichtemna
Created April 28, 2016 11:26
Show Gist options
  • Save nichtemna/65970fbddeaa9e8a8211c13351da7e03 to your computer and use it in GitHub Desktop.
Save nichtemna/65970fbddeaa9e8a8211c13351da7e03 to your computer and use it in GitHub Desktop.
Adapter for spinner to show hint item when nothing chosen. Position of selected items is shifted for 1.
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class HintSpinnerAdapter<T> extends ArrayAdapter<T> {
public static final int HINT_COUNT = 1;
public static final int HINT_POSITION = 0;
private int hintColorRes, selectedColorRes;
public HintSpinnerAdapter(Context context, int resource, List<T> valuesList, T hint) {
super(context, resource);
List<T> list = new ArrayList<>();
list.add(0, hint);
list.addAll(valuesList);
addAll(list);
init();
}
public HintSpinnerAdapter(Context context, int resource, T[] array, T hint) {
super(context, resource);
List<T> list = new ArrayList<>();
list.add(0, hint);
list.addAll(Arrays.asList(array));
addAll(list);
init();
}
private void init() {
hintColorRes = Color.GRAY;
selectedColorRes = Color.BLACK;
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
TextView view;
if (position == 0) {
TextView textView = new TextView(getContext());
textView.setHeight(0);
textView.setVisibility(View.GONE);
view = textView;
} else {
view = (TextView) super.getDropDownView(position, null, parent);
}
parent.setVerticalScrollBarEnabled(false);
return view;
}
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
if (view instanceof TextView) {
((TextView) view).setTextColor(position == HINT_POSITION ? hintColorRes : selectedColorRes);
}
return view;
}
public void setHintColorRes(int hintColorRes) {
this.hintColorRes = hintColorRes;
}
public void setSelectedColorRes(int selectedColorRes) {
this.selectedColorRes = selectedColorRes;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment