【问题标题】:ImageButton. How to have the standard "glow" efect when pressed图像按钮。按下时如何产生标准的“发光”效果
【发布时间】:2016-02-14 06:37:56
【问题描述】:

我有一个带有透明图像的 ImageButton。我更改了 ImageButton 的背景颜色。

当按下具有默认颜色的 ImageButton 时,该按钮会通过“发光”显示它已被按下了很短的时间。但是当背景颜色改变时,“发光”效果不会显示出来。不同的行为与图像无关,因为当按钮具有标准的“灰色”颜色时会显示“发光”效果。

如何在彩色图像按钮中获得“发光”效果?

附:我知道如何在单击事件上更改 ImageButton 的颜色。但我希望使用默认的灰色 ImageButton 具有相同的效果。 同样的事情(发光不显示)也发生在 Button 对象上。

【问题讨论】:

    标签: android imagebutton


    【解决方案1】:

    你可以使用这个库

    RippleView

    【讨论】:

    • 我宁愿恢复标准行为。你知道为什么它会消失然后改变背景颜色吗?
    • 当您更改背景颜色时,默认样式将不再起作用。
    【解决方案2】:

    您可以使用ColorStateList 定义按钮的pressed 颜色。

    您应该查看我上面链接的文档以了解详细信息。这是文档中的一个简单示例,涵盖了基础知识:

    XML 文件保存在 res/color/button_text.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_pressed="true"
              android:color="#ffff0000"/> <!-- pressed -->
        <item android:state_focused="true"
              android:color="#ff0000ff"/> <!-- focused -->
        <item android:color="#ff000000"/> <!-- default -->
    </selector>
    

    此布局 XML 会将颜色列表应用于视图:

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/button_text"
        android:textColor="@color/button_text" />
    

    在您的情况下,您需要将 android:background 设置为指向您的新 XML 资源,而不是 android:textColor

    希望对您有所帮助。

    【讨论】:

      【解决方案3】:

      android将发光效果作为透明背景资源,所以我通过在按钮后面放置一个彩色视图并将按钮背景设置为透明发光效果解决了这个问题。

      例如在我的xml中:

          <LinearLayout
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:background="@color/custom_color"
              android:orientation="vertical">
      
              <Button 
                  android:id="@+id/button"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"/>
          </LinearLayout>
      

      在我的 onCreate 中:

      TypedValue outValue = new TypedValue();
      getContext().getTheme().resolveAttribute(R.attr.selectableItemBackground, outValue, true);
      Button mButton = (Button) findViewById(R.id.button);
      mButton.setBackgroundResource(outValue.resourceId);
      

      仅当您的LinearLayout 中只有一个按钮时,它才有效,如果您想放其他东西,您可以使用RelativeLayout 中的视图,其参数与您的按钮相同。

      如果您还有其他问题,请告诉我!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多