我有一些图像按钮,我想添加一些图标(示例中为红色圆圈):
但我不知道如何对齐这个小图标。我有一个Button选择器(使用背景):
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/round_button_pressed" /> <!-- pressed -->
<item android:state_focused="true" android:drawable="@drawable/round_button_pressed" /> <!-- focused -->
<item android:drawable="@drawable/round_button" /> <!-- default -->
<item android:state_enabled="false" android:drawable="@drawable/round_button_deactivated" />
<item android:state_activated="false" android:drawable="@drawable/round_button_deactivated" />
</selector>
和一个shape.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<gradient
android:startColor="@color/button_main"
android:endColor="@color/button_main"
android:angle="270" />
<stroke
android:width="0px"
android:color="#000000" />
</shape>
有没有人知道我应该在哪里刊登我的图标,以便在我的图片按钮下方显示这个小图标?
答案 0 :(得分:0)
你可以做的是创建一个自定义可绘制类,它允许你绘制你的图像和你想要的任何其他东西,然后将该类设置为你的ImageButton的图像。
public class StackedImage extends Drawable {
private Drawable _drawable;
/* CONSTRUCTOR */
public StackedImage(Drawable drawable) {
super();
_drawable = drawable;
invalidateSelf();
}
/* ON DRAW */
@Override
public void draw(Canvas canvas) {
// Draw main image
_drawable.setBounds(0, 0, canvas.getWidth, canvas.getHeight);
_drawable.draw(canvas);
// Draw anything else you may want
// E.g. canvas.drawCircle(...)
}
@Override public void setAlpha(@IntRange(from = 0, to = 255) int alpha) {}
@Override public void setColorFilter(@Nullable ColorFilter colorFilter) {}
@Override public int getOpacity() { return PixelFormat.UNKNOWN; }
}
您甚至可以将多个图像作为背景的一部分,只需将更多可绘制内容传递给构造函数并将其边界更改为所需的位置即可。
然后在您的MainActivity中(或者您处理ImageButton的任何地方),执行以下操作:
Drawable icon = getResources().getDrawable(R.drawable.icon, null)
StackedImage stackedImage = new StackedImage(icon);
ImageButton myButton = findViewById(R.id.button)
myButton.setImageDrawable(stackedImage);
希望有所帮助!