1 /* 2 * Copyright (c) 2021 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_CHECKABLE_RADIO_GROUP_COMPONENT_H 17 #define FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_CHECKABLE_RADIO_GROUP_COMPONENT_H 18 19 #include "core/components/checkable/checkable_component.h" 20 21 namespace OHOS::Ace { 22 23 template<class T> 24 class RadioGroupComponent { 25 public: AddRadio(const RefPtr<RadioComponent<T>> & radio)26 void AddRadio(const RefPtr<RadioComponent<T>>& radio) 27 { 28 if (radio) { 29 radio->SetGroupValueChangedListener(groupValueChangedListener_); 30 radios_.push_back(radio); 31 } 32 } 33 RemoveRadio(const RefPtr<RadioComponent<T>> & radio)34 void RemoveRadio(const RefPtr<RadioComponent<T>>& radio) 35 { 36 radios_.remove(radio); 37 } 38 IsEmpty()39 bool IsEmpty() 40 { 41 return radios_.empty(); 42 } 43 SetIsDeclarative(bool isDeclarative)44 void SetIsDeclarative(bool isDeclarative) 45 { 46 isDeclarative_ = isDeclarative; 47 } 48 49 private: 50 const std::function<void(T)> groupValueChangedListener_ = [this](T newValue) { 51 std::string name = ""; 52 for (const auto& radio : radios_) { 53 auto refPtr = radio.Upgrade(); 54 if (refPtr) { 55 groupName_.push_back(refPtr->GetGroupName()); 56 if (newValue == refPtr->GetValue()) { 57 name = refPtr->GetGroupName(); 58 } 59 } 60 } 61 uint32_t counts = 0; 62 counts = count(groupName_.begin(), groupName_.end(), name); 63 for (const auto& radio : radios_) { 64 auto refPtr = radio.Upgrade(); 65 if (refPtr) { 66 if (isDeclarative_) { 67 if (counts > 1) { 68 refPtr->SetGroupValue(newValue); 69 refPtr->UpdateGroupValue(newValue); 70 } else { 71 if (refPtr->GetOriginChecked()) { 72 refPtr->SetGroupValue(newValue); 73 } else { 74 refPtr->SetGroupValue(" "); 75 } 76 } 77 } else { 78 refPtr->SetGroupValue(newValue); 79 refPtr->UpdateGroupValue(newValue); 80 } 81 } 82 } 83 groupName_.clear(); 84 }; 85 std::list<WeakPtr<RadioComponent<T>>> radios_; 86 std::list<std::string> groupName_; 87 bool isDeclarative_ = false; 88 }; 89 90 } // namespace OHOS::Ace 91 92 #endif // FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_CHECKABLE_RADIO_GROUP_COMPONENT_H 93