0

所以我想知道如何实现一个带有徽标按钮的操作栏,每个状态都有不同的图像。(按下,释放等)。

我知道如何为普通按钮执行此操作,但我不确定操作栏徽标按钮是否可行?

如果不是,如何实现支持此功能的操作栏?外部库?

谢谢你。

4

3 回答 3

3

创建一个可绘制的 xml 文件,res/drawable例如res/drawable/button_selector.xml

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

wherebutton_pressedbutton_normal只是您的可绘制目录之一中的常规 png 文件(例如/ drawables-hdpi

然后在你的 menu.xml 或你的代码中你可以参考 @drawable/button_selectoror R.drawable.button_selector并且当按钮被按下时图像会自动改变。

如果您需要更改 ActionBar 按钮背景,则需要覆盖res/values/style.xml.

<style name="YourTheme.Sherlock" parent="@style/Theme.Sherlock">
    <item name="actionBarItemBackground">@drawable/actionbar_item_background_selector</item>
    <item name="android:actionBarItemBackground">@drawable/actionbar_item_background_selector</item>
</style>

两条线都很重要:一条用于 SherlockActionBar,一条用于标准 ActionBar

然后将主题设置为清单中的活动:

   <activity
        android:name=".yourActivity"
        android:theme="@style/YourTheme.Sherlock" >
    </activity>

这里actionbar_item_background_selector.xml将被放置在res/drawable

<selector xmlns:android="http://schemas.android.com/apk/res/android">

<!-- Even though these two point to the same resource, have two states so the drawable     will invalidate itself when coming out of pressed state. -->
    <item android:state_focused="true"  android:state_enabled="false" android:state_pressed="true" android:drawable="@drawable/scene_overlay_bar_pressed_center"     />
    <item android:state_focused="true"  android:state_enabled="false"                                  android:drawable="@drawable/abs__list_selector_disabled_holo_light" />
    <item android:state_focused="true"                                android:state_pressed="true" android:drawable="@drawable/scene_overlay_bar_pressed_center" />
    <item android:state_focused="false"                               android:state_pressed="true" android:drawable="@drawable/scene_overlay_bar_pressed_center" />
    <item android:state_focused="true"                                                             android:drawable="@drawable/abs__list_focused_holo" />
    <item                                                                                          android:drawable="@android:color/transparent" />

</selector>

用您选择的可绘制对象替换背景android:state_pressed="true"

仅仅为了一个背景要做很多事情,但这就是ActionBar工作原理。

于 2012-12-03T04:17:05.097 回答
1

您可以使用选择器来选择不同的图像。 具有禁用 UI 感觉的 Android ImageButton 可能会有所帮助

于 2012-12-03T03:32:49.617 回答
0

我想你正在寻找这个:

final ActionBar bar = getActionBar();
bar.setDisplayHomeAsUpEnabled(true);

这会自动使您设置的徽标在单击时看起来像被按下。不需要有不同的图像来显示状态变化。这是一个很简单的方法。虽然如果您使用的是 ActionBarSherlock,我认为这是行不通的。我相信严格 4.0。查看ActionBar上的文档。

于 2012-12-03T04:40:10.183 回答