代码
对于我的应用程序中的结帐,我让用户通过在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。单击在我的“预付费/信用卡”单选按钮上,可以完美显示匹配视图
2。在我的Prepaid / CreditCard单选按钮上单击,它什么也没做
3。单击,在我的Prepaid / CreditCard单选按钮上,它会颠倒视图:“ prepaid”显示CreditCard布局,“ creditcard”显示我PrepaidPay Layout
这是布局问题吗(我应该实现ViewSwwichter / ViewPager)还是我的代码有错误?
谢谢
答案 0 :(得分:1)
而不是每个RadioButton
尝试在RadioGroup
上设置侦听器
payment_method.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId)
{
RadioButton checkedRadioButton = (RadioButton)group.findViewById(checkedId);
if(checkedRadioButton.isChecked()) {
if (checkedId == R.id.radio_prepaid)
{
relativeLayout_card.setVisibility(View.GONE);
cl_prepaid.setVisibility(View.VISIBLE);
}
else if (checkedId == R.id.radio_creditcard)
{
cl_prepaid.setVisibility(View.GONE);
relativeLayout_card.setVisibility(View.VISIBLE);
}
}
}
});
答案 1 :(得分:0)
尝试为每个按钮实现一个侦听器。它更易于阅读并减少了代码。否,如果分支。
您可以在无线电组的每个setOnCheckedChangeListener((compoundButton,b)-> {})或更高版本中编写一个lambda。
由于缺少视图层次结构,可见性问题并没有真正解决。