1

I want to display a spinner on the screen only if a radio button is clicked but I couldn't find a solution. Here is my current code.

    RadioGroup radio_grp=(RadioGroup) rootView.findViewById(R.id.radio_grp);
    RadioButton rb1 = (RadioButton) rootView.findViewById(R.id.radioButton1);
    RadioButton rb2 = (RadioButton) rootView.findViewById(R.id.radioButton2);



    View.OnClickListener button1Listener = new View.OnClickListener() {
        public void onClick(View v) {
            // Toast message etc.
        }
    };

    View.OnClickListener button2Listener = new View.OnClickListener() {
        public void onClick(View v) {
            // I want to show a spinner if they click the second radio button

        }
    };

    rb1.setOnClickListener(button1Listener);
    rb2.setOnClickListener(button2Listener);

    return rootView;
Vucko
  • 7,371
  • 2
  • 27
  • 45
Ege Kuzubasioglu
  • 5,991
  • 12
  • 49
  • 85
  • design your layout file with spinner with property visibility='gone' or 'invisible' and when you click the radio button make it visible – arjunkn Aug 19 '16 at 11:20

2 Answers2

2

First initialize the spinner like:

Spinner mSpinner = (Spinner) rootView.findViewById(R.id.mSpinner);

Of course, before that, add a spinner in your layout somewhere, and set it's android:visibility="invisible" if the first selected radio button is 1, else set it to visible. Then add listeners:

View.OnClickListener button2Listener = new View.OnClickListener() {
    public void onClick(View v) {
        // I want to show a spinner if they click the second radio button
        if (v.getId() == R.id.radioButton1) mSpinner.setVisibility(View.INVISIBLE);
        if (v.getId() == R.id.radioButton2) mSpinner.setVisibility(View.VISIBLE);

    }
};

If you don't want it to occupy any space once it's not on the screen, use View.GONEinstead of View.INVISIBLE. Refer here for the difference.

Community
  • 1
  • 1
Vucko
  • 7,371
  • 2
  • 27
  • 45
  • This seems like a good implementation. Might want to reference View.GONE and how View.INVISIBLE may be better for the OP, or let them decide. – Subby Aug 19 '16 at 11:23
-1

Put ((Spinner) findViewById(R.id.mySpinner)).performClick(); in second radiobutton click

View.OnClickListener button2Listener = new View.OnClickListener() {
            public void onClick(View v) {

    ((Spinner) findViewById(R.id.mySpinner)).performClick();
            }
        };
Zeeshan Khan
  • 553
  • 7
  • 11