使用单选按钮切换相对布局可见性

时间:2021-02-04 14:49:24

标签: java android android-studio

我遇到了一个奇怪的问题: 我一直在制作我的第一个安卓应用程序——一个简单的体脂计算器。其中一项功能要求,如果用户选择他的性别为“男性”,则需要输入臀围的布局应该不可见。反之亦然。问题是,当检查“男性”单选按钮时,布局确实消失,但是当检查“女性”单选按钮时,视图不会回来!为什么? Function

     genderGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            RadioButton radioButton = findViewById(genderGroup.getCheckedRadioButtonId());
            calculator.setGender(radioButton.getText().toString());
            Log.d("log", radioButton.getText().toString());
            if(radioButton.getText() == "Female"){
                hip_layout.setAlpha(0.0f);
            }
           else{
                hip_layout.setAlpha(1.0f);
            }
            toaster(calculator.getGender());
        }
    });

1 个答案:

答案 0 :(得分:1)

选中单选按钮并相应地设置可见性

genderGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                for (int rb_index=0;rb_index<genderGroup.getChildCount();rb_index++)
                {
                    Log.e("RADIOBUTTON :",""+rb_index+"/"+genderGroup.getChildCount());

                    RadioButton rb=((RadioButton) genderGroup.getChildAt(rb_index));
                    if(rb.isChecked()&&rb.getTag().toString().equalsIgnoreCase("male")){
                        Log.e("RADIOBUTTON :"," OK "+rb_index);

                         hip_layout.setVisibility(View.VISIBLE);
                    }
                      if(rb.isChecked()&&rb.getTag().toString().equalsIgnoreCase("female")){

                          hip_layout.setVisibility(View.INVISIBLE);
                    }
                }


            }
        });

对于您的布局:

<RadioGroup
    android:layout_width="wrap_content"
    android:id="@+id/rdg"
    android:layout_height="wrap_content">

    <RadioButton
        android:id="@+id/male"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:tag="male"
        android:text="Male"/>
 <RadioButton
     android:id="@+id/female"
     android:tag="female"

     android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Female"/>
</RadioGroup>