在Fragment的每个方向更改时调用SwitchCompat OnCheckedChangeListener

时间:2019-01-20 21:13:57

标签: android android-fragments orientation-changes oncheckedchanged switchcompat

我有一个托管片段的活动,问题是,在每次方向更改时,仅当开关处于检查状态时,才调用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();
                }
            }
        });
    }
}

1 个答案:

答案 0 :(得分:0)

我发现的一个解决方案是,在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
        }
    }
}

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