19

我使用带有光标适配器的下拉微调器。它包含例如 1 - 100 个项目。我选择例如项目 50。项目被选中。下次当我打开微调器时,第一个可见行是第 50 项。当我打开微调器时,如何实现它会聚焦到第一个项目/第一个可见项目将是第 1 项?

我的意思是像在列表中自动向上滚动一样,所以下拉列表中的第一个可见项目是第一个而不是选中的。

4

3 回答 3

37

您可以Spinner通过扩展它并覆盖负责设置/显示值列表的两种方法来做您想做的事情:

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;
    }

}

它应该适用于您想要做的事情。

于 2012-09-27T07:30:33.960 回答
2

您可以将 Spinner 的选择设置为第一项,如下所示:

yourspinner.setSelection(0);

您可能希望在 onStart() 方法中执行此操作。

于 2012-09-21T10:18:06.297 回答
1

这段简短的代码将为您完成工作。

    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);
        }
    });
于 2012-09-21T10:37:57.520 回答