使用单选按钮上的OnCheckedChangeListener反向显示/隐藏布局

问题描述 投票:0回答:2

代码

对于我的应用程序中的结帐,我让用户通过在RadioButton组中选择付款方式来决定他要使用的付款方式:

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

            <RadioButton
                android:id="@+id/radio_prepaid"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="prepaid"
                android:tag="prepaid"
                />

            <RadioButton
                android:id="@+id/radio_creditcard"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="creditcard"
                android:textAllCaps="true"
                android:tag="creditcard"
                />
        </RadioGroup>

从用户选择中,我要显示或隐藏匹配的布局:

    <RelativeLayout
    android:id="@+id/relativeLayout_card"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:visibility="gone"
    >
    ...
    </RelativeLayout>

<androidx.constraintlayout.widget.ConstraintLayout
    android:id="@+id/cL_preapid"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:visibility="gone"
    >
...
</ConstraintLayout>

我使用这部分代码:

    CompoundButton.OnCheckedChangeListener onPaymentChangedListener = (compoundButton,b) -> {

      if(compoundButton.getTag().equals("prepaid")) {
          relativeLayout_card.setVisibility(View.GONE);
          cl_prepaid.setVisibility(View.VISIBLE);

      }
      if(compoundButton.getTag().equals("creditcard")) {
          cl_prepaid.setVisibility(View.GONE);
          relativeLayout_card.setVisibility(View.VISIBLE);
      }

    };

    rb_creditcard.setOnCheckedChangeListener(onPaymentChangedListener);
    rb_prepaid.setOnCheckedChangeListener(onPaymentChangedListener);

问题

1。 CLICK在我的Prepaid / CreditCard单选按钮上,可以完美显示匹配视图

2。单击在我的预付/信用卡单选按钮上,它什么也不做

3。 CLICK在我的Prepaid / CreditCard单选按钮上,它反转了视图:“ prepaid”显示了CreditCard布局,“ creditcard”显示了我的PrepaidPay布局

这是布局问题吗(我应该实现ViewSwwichter / ViewPager)还是我的代码有错误?

谢谢

java android xml android-layout android-radiobutton
2个回答
0
投票

代替每个RadioButton尝试在RadioGroup上设置监听器>

payment_method.setOnCheckedChangeListener(onPaymentChangedListener)

0
投票

尝试为每个按钮实现一个侦听器。它更易于阅读并减少了代码。没有,如果分支。

© www.soinside.com 2019 - 2024. All rights reserved.