【问题标题】:Android: how to draw an ImageButton using the pressed state drawable for the focused stateAndroid:如何使用按下状态可绘制用于聚焦状态的 ImageButton
【发布时间】:2011-06-17 08:20:36
【问题描述】:

我正在尝试实现一种效果,一旦按下,ImageButton 就会以“按下”的橙色背景绘制,直到它失去焦点(触摸其他东西)。

StateListDrawable 似乎适用于这种情况,因为它可以让我定义如何为焦点状态绘制背景。如果我可以简单地定义背景应该使用按下的可绘制对象绘制,那将是很棒的,用于聚焦状态。但是,我认为没有办法引用默认的“按下”drawable。

关于如何实现这种效果的任何建议?

【问题讨论】:

    标签: android button background


    【解决方案1】:

    如果我理解你的问题也许可以帮助你

    我做同样的任务定义一个xml背景选择器,它包含每个状态的drawables,这个文件更广泛,因为你可以定义drawables,形状等......最重要的特点是你可以设置任何drawable或你想要的形状...

    在这里我定义了我的背景选择器......我称之为 selector.xml 并保存到可绘制文件夹中。

    <?xml version="1.0" encoding="utf-8"?>
        <selector xmlns:android="http://schemas.android.com/apk/res/android">
            <item android:state_selected="true" android:drawable="@drawable/shape_7"/>
            <item android:state_pressed="true" android:drawable="@drawable/shape_7" />
            <item android:state_pressed="false" android:drawable="@drawable/shape_6" />
        </selector>
    

    稍后当我构建 ImageButton 时,我会附加上面提到的选择器...(您可以通过编程方式或在您的 xml 布局中执行)

    ImageButton imageButton = new ImageButton(this);
    imageButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.selector));
    

    或者xml方式

    <ImageView
        android:background="@drawable/selector"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="4px"
        android:src="@drawable/switch_icon"/>
    

    干杯

    【讨论】:

    • 这很有帮助,但是,可能主要问题是我希望选择和按下和聚焦的可绘制对象成为 android 默认值。无论如何定义 shape_7 和 shape_6 以便它们使用默认的 android drawalbes? (当我说默认的 android drawables 时,我的意思是在未设置自定义背景时使用的那些)
    【解决方案2】:

    查看 android SDK 内的 drawables 文件夹。您可以找到它默认使用的所有九个补丁图像。您想要的可能称为 btn_pressed、btn_focused 等。或类似的名称。从技术上讲,您可以在项目中通过 id 引用它们,但我认为建议您将它们复制到您的项目中,因为这些 ID 不能保持不变。

    【讨论】:

    • 谢谢。我将此标记为已回答,因为它确实回答了我的问题,但实际上并没有解决我的问题。问题原来是 imagebutton 失去关注触摸的“向上”事件。我希望图像按钮保持焦点,直到其他东西抓住它(以便它绘制为焦点,直到其他东西被触摸)。对此有何建议?
    • 尝试在 onClickListener() 的 onClick(View v) 方法中为按钮调用 yourButton.requestFocus()。
    • @ab11 将您的按钮设置为在触摸模式下可聚焦developer.android.com/reference/android/view/… android:focusableInTouchMode="true"
    【解决方案3】:

    这对我的应用的 Holo Dark 主题很有效,但它没有我想要的圆角边缘。

    res/drawable/image_button_background.xml:

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@android:color/holo_blue_dark" android:state_pressed="true"/>
    </selector>
    

    用作:

    android:background="@drawable/image_button_background"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-04
      • 2011-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多