Android Studio:按钮上的 PNG

Android Studio: PNG on Button

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

但在xml中它位于按钮的中央,因此非常完美且拉伸得很好

android:drawableTop="@drawable/x"

在MainActivity中我不知道该做什么

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

使用下面的代码:

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); 

希望对您有所帮助。

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

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

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

祝你好运!