Android: 如何检查另一个 class 的开关是否在当前 class 中被选中以对其执行其他操作

Android: How can I check if a switch from another class is checked in a current class to perform other operations on it

我有 4 个片段,即:DashboardFragment.javaAlertsFragment.javaManualControls.javaAutomatedControls.java。 我在 ManualControls.java 中有一个开关,用于以下代码片段:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view=inflater.inflate(R.layout.fragment_manual_controls, container, false);

        switchLED= (Switch)view.findViewById(R.id.LEDSwitch1);
        switchLED.setChecked(false);
        switchLED.setTextOn("On");
        switchLED.setTextOff("Off");

//some codes about initializing a connection to my microcontroller to turn the LED on/off

 if(switchLED.isChecked()){
                        payload1="ledOn";
                    }

                    else{
                        payload1="ledOff";
                    }

额外信息:

在 AlertsFragment.java 中,我有一个下拉微调器,它有一些值(传感器阈值)。用户从下拉列表中选择一个值,将该值与从云端接收的传感器值进行比较,然后如果传感器值大于在微调器中选择的传感器阈值,则会发出警报。

AlertsFragment.java 如果未选中 ManualControls.java 的开关,我想发出警报。 switchLedManualControls.java 的转换。

switchLED= (Switch)view.findViewById(R.id.LEDSwitch1);

 if (!switchLED.isChecked()&&(ldrValue>spinnerValue)){
   //perform action
}

我想知道这是否是正确的方法,因为我现在没有我的暴徒来测试它,我不确定这种方法是否正确。

如果您在同一个 activity 中使用这四个片段,则将开关对象放入 activity 并正确初始化,这样您就可以访问所有四个片段中的开关位置。

如果您在单个 activity,

中使用

在您的 activity 中声明一个开关为

public Switch mySwitch;

在您的片段中,您可以在 ManualControl.Java

中初始化开关
((YourActivity)getActivity()).mySwitch= (Switch)view.findViewById(R.id.LEDSwitch1);

然后在AlertFragment.Java中访问它,

if (! ((YourActivity)getActivity()).mySwitch.isChecked()&&(ldrValue>spinnerValue)){
   //perform action
}

确定,当交换机初始化的时候。您可以检查它是否为空,然后在 AlertFragment.

中执行操作