java - 使用 RadioButton 上的 OnCheckedChangeListener 反向显示/隐藏布局
问题描述
编码
对于我的应用程序中的结帐,我让用户通过在 RadioButton Group 中选择来决定他想要使用的付款方式:
<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 RadioButton 它什么都不做
3. 点击我的 Prepaid / CreditCard RadioButton 它反转视图:“prepaid”显示 CreditCard 布局,“creditcard”显示 PrepaidPay 布局
这是布局的问题(我应该实现 ViewSwwichter / ViewPager)还是我的代码中有错误?
谢谢
解决方案
而不是每次都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);
}
}
}
});
推荐阅读
- vue.js - vue 项目在 dist 中包含 htaccess 文件
- excel - VBA中一个参数具有OR条件的countifs的正确语法是什么?
- javascript - 如何在 React/Redux/OIDC 中正确获取用户信息
- kotlin - 如何在 Kotlin 和 Project Reactor 中的 Flux 或 Mono 对象上内联函数映射
- assembly - 如何在汇编代码中访问开关的输入
- angular-cli - 为什么 Angular CLI@7.3.9 在创建库组件时不会用新的测试目标更新 angular.json
- swift - 如何访问函数prepare for segue的sender参数的systemItem信息?
- javascript - 是否可以在现有服务器上使用服务器端渲染?
- javascript - Angular 将 js 函数的值读取为未定义,即使对象具有值
- swift - 如何使用 Parse 服务器或直接在 MongoDB 上运行批处理“sql”?