带有图像和文字的Android ImageButton

3

我希望有一个按钮,顶部有一张图片,底部有一些文本。这些图片和文本都是在运行时决定的,因此我希望能够将ImageButton的setImageBitmap和Button的setText组合起来使用。

有什么好的想法吗?

谢谢 Chris


重复:https://dev59.com/8nI_5IYBdhLWcg3wFu7L - ognian
我在提问之前看了那个问题,但是我不能使用那里指定的答案,因为:
  1. 我无法将图像设置为背景,我希望图像在顶部,文本在底部,而不是文本覆盖图像。
  2. 我需要以编程方式设置事物,不能使用 XML。
- Chris
那么请查看我在另一个重复问题中的回答:http://stackoverflow.com/questions/3148713/inflating-a-view-into-button/3149052#3149052 - ognian
4个回答

3

将图像按钮和文本视图代码都放在...中,以覆盖图像按钮背景上的文本。即:

 <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <ImageButton
            android:id="@+id/imageButton1"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_marginLeft="69dp"
            android:layout_marginTop="96dp"
            android:background="@drawable/icon"
            android:scaleType="fitXY" />

        <TextView
            android:id="@+id/text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="Droid"
            android:textColor="#ff0000"
            android:textSize="24dip" >
        </TextView>
    </FrameLayout>

2

我终于找到了我要的东西:

setCompoundDrawablesWithIntrinsicBounds让我可以为按钮分配一个位图/可绘制对象,同时也让我可以使用setText。


这是针对带有文本和图像的按钮,而不是ImageButton的解决方案,因此这还不是原始问题的解决方案,而是一种变通方法。 - A-Live

1
例如:要在按钮上设置位图图像,请执行以下操作
button.setCompoundDrawablesWithIntrinsicBounds(null, new BitmapDrawable(bitmapimage), null, null);

0

我认为没有简单的方法可以做到这一点。

我会创建一个自定义组件


它可以通过XML布局完美地定义。 - ognian
@ognian:你可以使用XML布局来定义自定义组件。 - Macarse
是的,但我想说的是,没有必要创建另一个View子类,只是为了拥有一个带有图像和文本的按钮。 - ognian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接