Change the visibility of a layout’s fields at runtime

Asked

Viewed 738 times

0

In a layout for client registration, there are the specific fields for Legal Entities and Individuals. Control of the type of registration is done by RadioButton who are inside a RadioGroup.

I needed that when selecting the RadioButton of a Natural Person, the fields relating to a Legal Person are not visible on the screen and vice versa.

I’m trying to change the property Visibility from the fields to gone when an option is checked, but nothing is happening.

It is possible to carry out this control through the RadioButton?

Follows code from RadioGroup

RadioGroup group = (RadioGroup) findViewById(R.id.rgTipoEmpresa);
        group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                boolean rbFisica = R.id.rbFisica == checkedId;
                boolean rbJuridica = R.id.rbJuridica == checkedId;

                if (rbFisica){
                    etCNPJ.setVisibility(2);
                    etInscricao.setVisibility(2);
                    tvCNPJ.setVisibility(2);
                    tvInscricao.setVisibility(2);
                }

                if (rbJuridica){
                    etCPF.setVisibility(2);
                    etRG.setVisibility(2);
                    tvCPF.setVisibility(2);
                    tvRG.setVisibility(2);

                }
            }
        });

1 answer

3


Do not use values explicitly when there are constants defined for this purpose.
The class View declares the following constants to be used in the method setVisibility(), to define its visibility:

View.VISIBLE    // valor 0
View.INVISIBLE  // valor 4
View.GONE       // valor 8

Using constants prevents errors and makes code more readable.

etCNPJ.setVisibility(View.GONE);

In your code you use the value 2 that is not a valid value. (See documentation).

Also do not forget that when one is selected RadioButton, besides making "GONE" items that do not apply to that situation must become "VISIBLE" the items that apply.

A simple way to reverse the visibility is used by the operator ^ (XOR):

etCNPJ.setVisibility(etCNPJ.getVisibility() ^ View.GONE);

After the execution of this line etCNPJ will become VISIBLE if he was GONE or GONE if he was VISIBLE.

  • Perfect. I ended up confusing the setVisibility with the android:visibility.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.