我正在动态地在无线电组中创建无线电按钮。当使用保存的实例状态来设置在应用程序关闭之前选择了哪个单选按钮时,会检查正确的单选按钮,但它不会显示已检查的状态。通过记录数据,我知道它已被检查。它也很明显,因为点击时它不会更新。
当我设置在创建时检查的radiobutton没有重新创建实例状态时没有问题。
public class PaymentMethodsAdapter {
private static final String TAG = PaymentMethodsAdapter.class.getCanonicalName();
private LayoutInflater layoutInflater;
private RadioGroupPlus radioGroup;
private List<PaymentMethod> paymentMethods;
private int selectedPaymentMethod = -1;
public PaymentMethodsAdapter(RadioGroupPlus radioGroup, Context context) {
layoutInflater = LayoutInflater.from(context);
this.radioGroup = radioGroup;
radioGroup.setOnCheckedChangeListener(new RadioGroupPlus.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroupPlus radioGroupPlus, int i) {
selectedPaymentMethod = i;
}
});
}
public void setPaymentMethods(List<PaymentMethod> paymentMethods, int selectedPaymentMethod) {
this.selectedPaymentMethod = selectedPaymentMethod;
this.paymentMethods = paymentMethods;
radioGroup.removeAllViews();
for(int i = 0; i < paymentMethods.size(); i++) {
PaymentMethod paymentMethod = paymentMethods.get(i);
View v = layoutInflater.inflate(R.layout.view_payment_method, radioGroup, false);
RadioButton radioButton = v.findViewById(R.id.paymentMethodTitle);
radioButton.setId(i);
radioButton.setText(paymentMethod.getName());
TextView description = v.findViewById(R.id.paymentMethodDescription);
description.setText(paymentMethod.getDescription());
radioGroup.addView(v);
}
if(selectedPaymentMethod >= 0) {
radioGroup.check(selectedPaymentMethod);
}
}
public int getSelectedPaymentMethodPosition() {
return selectedPaymentMethod;
}
public PaymentMethod getSelectedPaymentMethod() {
if(selectedPaymentMethod >= 0) {
return paymentMethods.get(selectedPaymentMethod);
} else {
return null;
}
}
}
片段中的:
private void updatePaymentMethods() {
if(viewInflated && checkoutInfo != null) {
paymentMethodsAdapter.setPaymentMethods(checkoutInfo.getPaymentMethods(), selectedPaymentMethod);
paymentMethodsGroup.invalidate();
Log.i(TAG, "updating payment methods. selected: "+ selectedPaymentMethod);
}
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
if(savedInstanceState != null) {
selectedPaymentMethod = savedInstanceState.getInt(SELECTED_PAYMENT_METHOD_KEY, -1);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_checkout, container, false);
...
viewInflated = true;
updatePaymentMethods();
return v;
}