I have an activity which hosts a fragment and the problem is that, on every orientation change and only if the switch was in the checked state, the OnCheckedChangeListener
is called. How do I solve this problem? Thanks!
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();
}
}
});
}
}
One solution I found is to check, in the onCheckedChanged
method, if the buttonView
(the Switch) was actually toggled by the user and not after recovering the savedInstanceState
after an orientation change, for example:
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (buttonView.isPressed()) {
if (isChecked) {
// Handle the checked state
} else {
// Handle the NOT checked state
}
}
}
If there are more elegant answers, I'm totally waiting for them!