-2

I want to add and remove spinner on button click but the total no. of spinners should be only 3.

Hritik
  • 1
  • 1
    This is an easy task but the answer depends on what you have already written. Please read [ask] and then show us what you have tried for that read [mcve]. – Sam Jan 27 '18 at 20:05
  • One alternative would be to add the `Spinner` to your layout and toggle the Visibility to either `VISIBLE` or `GONE` – Barns Jan 27 '18 at 21:12

1 Answers1

0
  1. Create an onClickListener on the button
  2. In the onClick method you need to get the UI component which will be the container for the Spinner (f.e. a LinearLayout) with findViewById
  3. Create the Spinner new Spinner(this, mode) (mode is MODE_DIALOG or MODE_DROPDOWN)
  4. Set SpinnerAdapter providing the data for the Spinner with setAdapter(). The type of the adapter depends on the data you want to put there.
  5. Add this Spinner in the container by addView() (explore the params in the docs).

You can see an example of adding a view dynamically in this SO post.

Regarding the requirement of the amount limitation of the Spinners, you could simply track the current amount in a private field of the Activity you are working on. Of course you need to check the current amount before adding a new Spinner.

Removing a spinner is similar to adding one, just call removeView(View view) or removeViewAt(int index).


If you don't need to fill the Spinners with different data every time, i.e. you are sure that the first Spinner will have f.e. data "cat","dog","fish": You can get the reference to the Spinner and work with its visibility by setVisibility() setting it to VISIBLE INVISIBLE or GONE.

Hawk
  • 2,042
  • 8
  • 16