Android将图像添加到按钮

ste*_*ong 11 android image button

我想要添加一个图像Button(不imagebutton,因为特定按钮可以包含文本或图像;加上图像按钮有相同的问题),同时仍保留原始的android风格按钮.因此添加android:backgroundXML不会削减它,因为这将删除带有圆角等的android默认按钮.(android.R.drawable.btn_default)

这有可能吗?

我认为一种方法是9patch按下按钮的图像(一个用于向上,一个用于向下)并onTouch Action_DOWN制作一个分层的背景可绘制并将其放在按钮上,并做同样的事情,但另一个9patch用于onTouch Action_UP,但我认为这将大大降低了应用程序的性能,因为对于所有按钮点击(对我的应用程序来说,这将是非常多的)需要相当多的资源读取和图层合并.我上面说的是正确的吗?

编辑:我不能在XML中声明图像的来源,因为我从Web服务获取图像,所以任何东西都可以放在按钮上,但必须以编程方式进行.

Rid*_*lly 25

这可以通过使用来完成android:drawableTop,android:drawableBottom,android:drawableLeft,android:drawableRight属性在layout.xml.

  • 在代码中,您可以使用 - strangly named - 方法`setCompoundDrawablesWithIntrinsicBounds(int,int,int,int)`,如下所述:http://developer.android.com/reference/android/widget/TextView.html#setCompoundDrawablesWithIntrinsicBounds( int,int,int,int)< - 链接未被SO正确链接... (2认同)

Dhi*_*a k 10

在此输入图像描述

     <Button
            android:layout_width="0dp"
            android:layout_weight="1"
            android:background="@drawable/home_button"
            android:drawableLeft="@android:drawable/ic_menu_edit"
            android:drawablePadding="6dp"
            android:gravity="left|center"
            android:height="60dp"
            android:padding="6dp"
            android:text="AndroidDhina"
            android:textColor="#000"
            android:textStyle="bold" />
Run Code Online (Sandbox Code Playgroud)

了解更多信息http://androiddhina.blogspot.in/2015/09/how-to-add-image-inside-button.html


Dip*_*iya 8

设置在带有文本的显示图像的按钮的属性下方,使用此属性图像显示在上面的文本上.

<Button android:drawableTop="@drawable/ic_launcher"/>
Run Code Online (Sandbox Code Playgroud)