25
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Spinnerだけ動かして、OnItemSelectedは実行させない簡単な方法

Posted at

Spinnerを動かすと、SpinnerにセットされたOnItemSelectedListenerからonItemSelectedが実行されます。初回起動時にSpinnerのpositionだけ任意の値に動かして, OnItemSelectedは動かさないようにする方法が意外に思いつかなかったので、Tipsとしてメモ。

###やりかた

Spinnerにlistenerをsetする前にsetSelectionします。また、setSelectionでonItemSelectedを起動しないように、falseオプションをつけることがミソです。

//listenerの設定
mListener = new AdapterView.OnItemSelectedListener() {

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        //やりたいことやる
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
       
    }
};

mModeSpinner = (Spinner)findViewById(R.id.spinner_nav);
SpinnerAdapter spinnerAdapter = ArrayAdapter.createFromResource(this, R.array.spinner_mode, android.R.layout.simple_spinner_dropdown_item);
mModeSpinner.setAdapter(spinnerAdapter);

//falseを設定して、onItemSelectedを呼ぶanimationを回避
mModeSpinner.setSelection(position, false);
//ここでリスナーをつける
mModeSpinner.setOnItemSelectedListener(mListener);

ついでですが、初回起動時以外でSpinnerを動かしつつonItemSelectedを起動しないためには、listenerを外してやります。

mModeSpinner.setOnItemSelectedListener(null);
mModeSpinner.setSelection(position, false);
mModeSpinner.setOnItemSelectedListener(mListener);

以上です。

25
25
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
25
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?