I use dropdown spinner with cursor adapter. It contains e.g 1 - 100 items. I select e.g. item 50. Item is selected. Next time when I open spinner first visible row is item 50. How can I achieve that when I open spinner it will focus to first item/first visible item will be item 1?
I mean like autoscroll up in the list, so first visible item in dropdown is 1st one and not selected one.
You can make the Spinner
do what you want by extending it and overriding the two methods that are responsible for setup/showing the list of values:
public class CustomSpinnerSelection extends Spinner {
private boolean mToggleFlag = true;
public CustomSpinnerSelection(Context context, AttributeSet attrs,
int defStyle, int mode) {
super(context, attrs, defStyle, mode);
}
public CustomSpinnerSelection(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
public CustomSpinnerSelection(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomSpinnerSelection(Context context, int mode) {
super(context, mode);
}
public CustomSpinnerSelection(Context context) {
super(context);
}
@Override
public int getSelectedItemPosition() {
// this toggle is required because this method will get called in other
// places too, the most important being called for the
// OnItemSelectedListener
if (!mToggleFlag) {
return 0; // get us to the first element
}
return super.getSelectedItemPosition();
}
@Override
public boolean performClick() {
// this method shows the list of elements from which to select one.
// we have to make the getSelectedItemPosition to return 0 so you can
// fool the Spinner and let it think that the selected item is the first
// element
mToggleFlag = false;
boolean result = super.performClick();
mToggleFlag = true;
return result;
}
}
It should work just fine for what you want to do.
You can set the selection of a Spinner to the first item like this:
yourspinner.setSelection(0);
You might want to do this in the onStart() method.
This short of code will do the work for you.
int prevSelection=0;
spSunFrom = (Spinner) findViewById(R.id.spTimeFromSun);
spSunFrom.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
prevSelection = spSunFrom.getSelectedItemPosition();
spSunFrom.setSelection(0);
return false;
}
});
spSunFrom.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
if(arg2==0)
spSunFrom.setSelection(prevSelection);
prevSelection = arg2;
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
spSunFrom.setSelection(prevSelection);
}
});
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