SwitchCompat OnCheckedChangeListener 调用 Fragment 的每个方向变化

SwitchCompat OnCheckedChangeListener called on every orientation change of Fragment

我有一个 activity,它承载一个片段,问题是,在每次方向改变时,只有当开关处于选中状态时,才会调用 OnCheckedChangeListener。我该如何解决这个问题?谢谢!

MainActivity.java:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
        if (savedInstanceState == null) {
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.container, new MainFragment())
                    .commit();
        }
    }
}

MainFragment.java

public class MainFragment extends Fragment {

    private SwitchMaterial switchMaterial;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.main_fragment, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        switchMaterial = view.findViewById(R.id.switch_material);
        switchMaterial.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    Toast.makeText(getContext(), "Switch is checked.", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getContext(), "Switch is NOT checked.", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

我找到的一个解决方案是在 onCheckedChanged 方法中检查 buttonView(开关)是否实际上由用户切换,而不是在恢复 savedInstanceState 之后方向改变,例如:

public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    if (buttonView.isPressed()) {
        if (isChecked) {
            // Handle the checked state
        } else {
            // Handle the NOT checked state
        }
    }
}

如果有更优雅的答案,我等着他们!