【问题标题】:How to reset other view style (button) or reset all button background in layout at once?如何重置其他视图样式(按钮)或一次重置布局中的所有按钮背景?
【发布时间】:2016-01-22 22:15:03
【问题描述】:

我在布局中有 3 个按钮。我希望当单击一个按钮时,其他 2 个按钮的样式设置为“默认”。在我的示例中:背景颜色。 按 button1 必须改变她的样式并重置其他按钮的样式。

最简单的解决方案是设置每个按钮的样式,在每个方法调用上,但这是最简单的解决方案,如果图层只有2-5个按钮,但如果有10-20个呢?

在 drawable/button_bg.xml 中,我有 2 种状态的选择器:默认和 state_selected。 是否可以在不重新加载应用的情况下立即重置(或设置)图层(布局)中所有按钮的所有样式?

或者,如果未按下按钮,则指定默认样式?或类似 layout.AllButtons.setDefaultStyle(true) 的东西(对不起) When click on one button, need to change styles for other

正如你现在看到的,在新点击其他按钮后 state_selected 不会重置。

【问题讨论】:

标签: android android-layout


【解决方案1】:

您可以通过迭代布局并设置所需的参数来手动完成,例如

private void unselectButtons(ViewGroup root, View except) {
    int childCount = root.getChildCount()
   for (int i=0; i < childCount; ++i) {
      View child = root.getChildAt(i);
      if (child instanceof ViewGroup) {
        unselectButtons((ViewGroup)child,except);
      } else if (child instanceof Button && child != except) {
        child.setSelected(false);
      }

   }


}

【讨论】:

  • 它正在工作。谢谢。但只有在方法 unselectButtons Integer count = root.getChildCount(); for (int i=0; i &lt; count; ++i) 中单独声明 count
猜你喜欢
  • 2020-07-17
  • 1970-01-01
  • 1970-01-01
  • 2012-09-05
  • 1970-01-01
  • 2012-05-21
  • 1970-01-01
  • 2020-12-08
  • 2023-02-26
相关资源
最近更新 更多