微调器 - 专注于第一项

van*_*dzi 17 android android-widget android-layout android-spinner

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

我的意思是像列表中的自动滚动一样,因此下拉列表中的第一个可见项目是第一个而不是一个.

Luk*_*rog 35

您可以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;
    }

}
Run Code Online (Sandbox Code Playgroud)

它应该适合您想要做的事情.

  • 很棒的答案!谢谢! (2认同)
  • 我一直在寻找这样的东西...... 3 年后,它仍然是很好的信息!谢谢芽。 (2认同)