19

カーソルアダプターでドロップダウンスピナーを使用しています。たとえば、1 ~ 100 個のアイテムが含まれます。たとえば、アイテム 50 を選択します。アイテムが選択されます。次回スピナーを開いたときに最初に表示される行はアイテム50です。スピナーを開いたときに最初のアイテム/最初に表示されるアイテムがアイテム1になるようにするにはどうすればよいですか?

リストを自動スクロールするようなものなので、ドロップダウンの最初に表示されるアイテムは最初のものであり、選択されたものではありません。

4

3 に答える 3

37

Spinnerそれを拡張し、値のリストの設定/表示を担当する2つのメソッドをオーバーライドすることで、必要なことを実行できます。

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

次のように、スピナーの選択を最初の項目に設定できます。

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 に答える