在Fragment的每个方向更改时调用SwitchCompat OnCheckedChangeListener [英] SwitchCompat OnCheckedChangeListener called on every orientation change of Fragment
问题描述
我有一个托管片段的活动,问题是,在每次方向更改时,仅当开关处于检查状态时,才调用OnCheckedChangeListener
.我该如何解决这个问题?谢谢!
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();
}
}
});
}
}
推荐答案
我发现的一个解决方案是在onCheckedChanged
方法中检查buttonView
(交换机)是否确实由用户切换了,而不是更改方向后恢复savedInstanceState
,例如:
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!
这篇关于在Fragment的每个方向更改时调用SwitchCompat OnCheckedChangeListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!