【问题标题】:setSelected() on ToggleButton does not change its appearanceToggleButton 上的 setSelected() 不会改变其外观
【发布时间】:2018-05-01 17:01:55
【问题描述】:

我在 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 改变外观?

【问题讨论】:

    标签: android android-togglebutton


    【解决方案1】:

    在尝试了很多不同的事情之后,我找到了在 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());
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2012-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-04
      • 2012-12-03
      相关资源
      最近更新 更多