【问题标题】:Android Studio: PNG on ButtonAndroid Studio:按钮上的 PNG
【发布时间】:2017-03-11 18:16:10
【问题描述】:

如何在 MainActivity 的按钮上设置 png 图标? 我在程序中要多次更改这个图标,所以无法在xml代码中设置图片。

但在 xml 中它位于按钮的中心,因此它完美且拉伸良好

android:drawableTop="@drawable/x"

在 MainActivity 我不知道该做什么

bt.setCompoundDrawablesWithIntrinsicBounds(null, x, null, null);

【问题讨论】:

    标签: android-studio button png drawable


    【解决方案1】:

    使用下面的代码:

    Drawable top = getResources().getDrawable(R.drawable.x);
    bt.setCompoundDrawablesWithIntrinsicBounds(null, top , null, null);
    

    要在中心添加图像,您可以使用 imageButton:

    在布局 xml 中添加下面的图像按钮代替您的按钮。

     <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/imageButton" />
    

    获取imageButton并设置drawable:

    ImageButton ib = (ImageButton)findViewById(R.id.imageButton);
    ib.setImageResource(R.drawable.x); 
    

    希望这会有所帮助。

    【讨论】:

    • 有没有办法改变宽度和高度?我怎样才能把这张图片放在按钮的中心?
    【解决方案2】:

    如果您的目标是 API 级别 17 或更高,只需一行简单的代码即可完成:

    bt.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.x , 0, 0);
    

    此方法以可绘制资源 ID 作为参数,因此无需使用 getDrawable() 自己获取可绘制资源。传递 0 作为参数意味着那一侧没有图标。

    祝你好运!

    【讨论】:

    • 我怎样才能把这张图片放在按钮的中心?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-02
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    相关资源
    最近更新 更多