【问题标题】:SwitchCompat OnCheckedChangeListener called on every orientation change of FragmentSwitchCompat OnCheckedChangeListener 调用 Fragment 的每个方向变化
【发布时间】:2019-01-20 21:13:56
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    我找到的一个解决方案是在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
            }
        }
    }
    

    如果有更优雅的答案,我完全在等待!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多