Android开发 - 自定义按钮外观/行为

时间:2011-05-12 18:06:58

标签: android button android-layout

我正在编写一个非常简单的Android应用程序。在这样做的过程中,我发现我很难模拟Droid X应用程序选择器屏幕上的按钮UI元素。对于那些不熟悉的人,他们是一个带有白色文字的图标。文本后面有一个黑色圆角矩形,单击按钮时,图标和文本下方的背景变为红色。

我当前的解决方案涉及StateListDrawables,但圆角矩形具有固定的宽度,并且必须编辑到每个按钮图标中。本地化是最终的目标,因此我的解决方案充其量只是暂时的。我认为有一种不那么愚蠢的方法吗?

1 个答案:

答案 0 :(得分:0)

我没试过,我从来没有见过你正在谈论的按钮。但这个过程应该是类似的。

首先创建可绘制的(实际背景图像)。一个是红色背景,一个是透明的。您的可绘制XML看起来像这样:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/btn_bg_red"/>
    <item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/btn_bg_red"/>
    <item android:state_focused="true" android:drawable="@drawable/btn_bg_pressed"/>
    <item android:state_focused="false" android:state_pressed="false" android:drawable="@android:color/transparent"/>
</selector>

然后您的按钮本身可以声明为与此类似:

<Button android:id="@+id/droid_x_btn"
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:text="Droid Does"
                android:drawableTop="@drawable/btn_icon" <!-- this is for the icon on top -->
                android:background="@drawable/ic_droid_x_button" <!-- The name of the above file without extension -->
                android:textColor="@color/white" />

希望这有帮助!

相关问题