LoginSignup
10
6

More than 5 years have passed since last update.

Spinnerでの選択肢の表示をコードからdismissできるようにする

Last updated at Posted at 2016-10-21

Spinnerでは、spinnerModeの設定によってdialogとdropdownで選択肢を表示できます。それらをコードからdismissしたい場合のメモです。

デフォルトではSpinnerにはdialog、dropdownをdismissするメソッドが用意されていません。そのためonDetachedFromWindowが呼ばれるとdialog、dropdownがdismissされることを利用してコードからdismissできるようにします。

具体的には、SpinnerもしくはAppCompatSpinnerを継承して以下のようなカスタムViewを作成します。

public class MySpinner extends AppCompatSpinner {

    public MySpinner(Context context) {
        super(context);
    }

    public MySpinner(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MySpinner(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

   public void dimissSpinnerOptions() {
        onDetachedFromWindow();
    }
}

使い方は、まずxmlに定義します。

<MySpinner
    android:id="@+id/my_spinner"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:spinnerMode="dropdown" />

そして、以下のようにコードからdimissSpinnerOptionsを実行します。これでコードからdismissできるようになります。

MySpinner mySpinner = (MySpinner) findViewById(R.id.my_spinner);
mySpinner.dimissSpinnerOptions();
10
6
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
10
6