SwitchCompat OnCheckedChangeListener called on every orientation change of Fragment

半城伤御伤魂 提交于 2019-12-08 09:02:01

问题


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();
                }
            }
        });
    }
}

回答1:


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!



来源:https://stackoverflow.com/questions/54281040/switchcompat-oncheckedchangelistener-called-on-every-orientation-change-of-fragm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!