如何在API 23+中从可绘制选择器中设置透明度?

3
我想将一个位图设置为ImageButton的src,并在按下时使其部分透明。但是,在选择器中使用android:alpha属性似乎没有任何效果。
我已经使用我的@drawable/all_close定义了一个StateListDrawable。
<?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/all_close" android:alpha="0.5" />
    <item android:drawable="@drawable/all_close" android:alpha="1.0" />
</selector>
<!-- have also tried alpha as 0 to 255, with the same result -->

我已将该可绘制对象设置为我的ImageButton的src属性:

<ImageButton
    android:src="@drawable/all_nav_close"
    android:background="@drawable/none"/>
<!-- some attributes omitted for space -->

当按下按钮时,按钮不会发生变化。选择器肯定被使用了,因为更改 state_pressed 的可绘制对象会明显改变按钮:
<?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/all_add" android:alpha="0.5" />
    <item android:drawable="@drawable/all_close" android:alpha="1.0" />
</selector>

然而,android:alpha 属性似乎对不透明度没有任何影响。项目构建和安装。该属性不会触发“未知属性”linter警告(和构建失败),但IDE也不建议使用它。这是在API 23上,使用 com.android.support:appcompat-v7:25.0.0com.android.support:design:25.0.0

图片是白色的PNG格式,背景透明,如果有帮助的话。 - David Lord
2个回答

1
你尝试过编程吗?我在我的应用程序中使用这个。
Paint paint = new Paint();
paint.setAlpha(100);
canvas.drawBitmap(bitmap, src, dst, paint);

但是...根据你的需要检查并更改内容,可以使用ImageView、Paint或Bitmap:

ImageView.setAlpha().
BitmapDrawable.setAlpha().

我刚刚试过了,使用.setAlpha(0.5f)确实可以使按钮变灰 - 感谢您的建议!因此,使用alpha可以达到我想要的效果;只是xml不能正确设置alpha(?)。我不想使用代码,因为这个模式将在多个地方使用,我宁愿使用Android样式而不是扩展ImageButton。 - David Lord

0

嗨,我已经用这种方式完成了,请检查一下, 当你进入屏幕时看看它是如何工作的

 @Override
public void centerScene(ImageView sharedElement) {
    binding.sharedImage.setTranslationY(0);
    setSharedImageRadius(binding.sharedImage, 0);

    binding.deviceImage.setAlpha(1.0f);
    binding.deviceText.setAlpha(1.0f);
    binding.deviceImage.setAlpha(1.0f);
    binding.deviceImage.setScaleX(1.0f);
}

当你退出屏幕时

 //position goes from -1.0 to 0.0
 @Override
 public void exitScene(ImageView sharedElement, float position) {
    binding.sharedImage.setTranslationY(
            getResources().getDimension(R.dimen.tutorial_shared_element_translate_y)
                    * position);

    setSharedImageRadius(binding.sharedImage, -position);

    binding.deviceText.setAlpha(1 + position);
    binding.deviceImage.setAlpha(1 + position);
    binding.deviceImage.setScaleX(1 - position); // stretch
}

@Override
public void notInScene() {
    binding.deviceImage.setAlpha(0.0f);
    binding.deviceText.setAlpha(0.0f);
}

如果您不想使用绑定,请将其替换为Butter Knife。

查看此示例以获取更多信息。您可以理解所有事情。


这展示了通过代码设置alpha,谢谢。我特别感兴趣的是通过XML设置alpha - Onboarding项目似乎没有这样做?数据绑定很好。 - David Lord

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