I've got basic android spinner and I would like to have, after clicking it, the list with items with one of them highlighted, the one, that was originally selected.
Like it's done here: http://www.warriorpoint.com/blog/wp-content/uploads/2009/05/05spinner-thumb.png
But with my own layout of the items and not with the radio box, but with my own background instead.
How can I achieve this? Is there anything of use in the selector, or do I have to do it programatically?
Any help is appreciated.
Below is an solution I tested and verified. You can use setSelection(N) to highlight the item you want.
class HighLightArrayAdapter extends ArrayAdapter<CharSequence> {
private int mSelectedIndex = -1;
public void setSelection(int position) {
mSelectedIndex = position;
notifyDataSetChanged();
}
public HighLightArrayAdapter(Context context, int resource, CharSequence[] objects) {
super(context, resource, objects);
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
View itemView = super.getDropDownView(position, convertView, parent);
if (position == mSelectedIndex) {
itemView.setBackgroundColor(Color.rgb(56,184,226));
} else {
itemView.setBackgroundColor(Color.TRANSPARENT);
}
return itemView;
}
}
public class MainActivity extends Activity {
Spinner mySpinner;
String[] myArray={"1","2","3","4","5"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mySpinner = (Spinner)findViewById(R.id.spinner_test);
mySpinner.setAdapter(new MyAdapter(this,android.R.layout.simple_spinner_item, myArray));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class MyAdapter extends ArrayAdapter<String>{
public MyAdapter(Context context, int textViewResourceId,
String[] objects) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
}
@Override
public View getDropDownView(int position, View cnvtView, ViewGroup prnt){
LayoutInflater inflater = getLayoutInflater();
View spinnerItem = inflater.inflate(android.R.layout.simple_spinner_item, null);
TextView mytext= (TextView)spinnerItem.findViewById(android.R.id.text1);
mytext.setText(myArray[position]);
//int selected = Spinner.
int selected = mySpinner.getSelectedItemPosition();
if(position == selected){
spinnerItem.setBackgroundColor(Color.BLUE);
}
return spinnerItem;
}
}
}
This should help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With