ToggleButton上的setSelected()不会改变其外观

时间:2018-05-01 17:01:55

标签: android android-togglebutton

我在Fragment子类中有一个ToggleButton,我只能在第一次调用setSelected() - 之后,当我用isSelected()调试时,setSelected()会改变属性,但是ToggleButton本身的外观确实如此不要改变。

在我的AddEditTripFragment中扩展了Fragment类:

public View onCreateView(@NonNull LayoutInflater inflater, @Nullable 
    ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_add_edit_trip, container, false);

    ...

    mondayButton = v.findViewById(R.id.mondayButton);
    final Trip myTrip = ((MainActivity)getActivity()).tripToEdit;
    // Check if tripToEdit is not null, so we can pull the values to populate the date/time
    if (myTrip != null) {
        ...
        mondayButton.setChecked(myTrip.isMonday());
        mondayButton.setSelected(myTrip.isMonday());
        Log.d(TAG, "onCreateView: myTrip.Monday() = " + myTrip.isMonday());
        Log.d(TAG, "onCreateView: mondayButton.isSelected() = " + mondayButton.isSelected());
        ...
    }

输出:

... onCreateView: myTrip.Monday() = true
... onCreateView: mondayButton.isSelected() = true

然而ToggleButton的外观仍然“被关闭”。

我还没有向ToggleButton添加任何监听器。

当我对其执行.setSelected()时,如何让ToggleButton更改外观?

1 个答案:

答案 0 :(得分:0)

经过大量尝试不同的事情之后,我找到了唯一能解决Github问题的解决方案:https://github.com/navasmdc/MaterialDesignLibrary/issues/199#issuecomment-89126286

替换

mondayButton.setChecked(myTrip.isMonday());
mondayButton.setSelected(myTrip.isMonday());

为此:

mondayButton.post(new Runnable() {
    @Override
    public void run() {
        mondayButton.setChecked(myTrip.isMonday());
        mondayButton.setSelected(myTrip.isMonday());
    }
});