如何设置在API级别7的整个视图的alpha值(Android 2.1的)视图、如何设置、级别、API

2023-09-06 15:29:13 作者:二货世界欢乐多

我有,我想淡入另一个视图顶部的任意视图。在API级别11我看到有一个setAlpha,但我卡支持的API 7级。我还没有穿过一个简单的方法来做到这一点运行。我怎样才能设置alpha为整个视图,而不与各个组件搞乱?

I have an arbitrary view that I want to fade in on top of another view. In api level 11 I see there is a setAlpha, but I'm stuck supporting api level 7. I haven't run across a simple way to do this. How can I set the alpha for the entire view without messing with each individual component?

推荐答案

使用AlphaAnimation将是最过渡的最佳解决方案,如果我不能找到一种方法,做的正是我努力一定会为我工作做的,其中基于所述装置的倾斜角在带刻度的方式的两个视图之间涉及衰落。幸运的是我有!这是我接过的策略:我包裹视图的FrameLayout的自定义子类,并实现OnDraw的。在那里,我捕获的子视图作为位图,然后重划与预期阿尔法位图。下面是一些code。我会编辑,当我得到清理,这是概念恰恰证明,但它就像一个魅力:

Using AlphaAnimation would be an excellent solution for most transitions, and would certainly have worked for me if I couldn't find a way to do exactly what I was trying to do, which involves fading between two views in a graduated way based on the tilt angle of the device. Fortunately I have! Here is the strategy I took: I wrapped the view in a custom subclass of FrameLayout, and implemented onDraw. There, I captured the child view as a bitmap, and then redrew the bitmap with the intended alpha. Here's some code. I'll edit when I get cleaned up, this is just proof of concept, but it works like a charm:

public class AlphaView extends FrameLayout {
    private int alpha = 255;

    public AlphaView(Context context) {
        super(context);
        setWillNotDraw(false);
    }

    public AlphaView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setWillNotDraw(false);
    }

    public AlphaView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setWillNotDraw(false);
    }

    public void setCustomAlpha(int alpha) {
        if (this.alpha != alpha) {
            this.alpha = alpha;
            invalidate();
        }
    }

    public int getCustomAlpha() {
        return alpha;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        for(int index = 0; index < getChildCount(); index++ ) {
            View child  = getChildAt(index);
            child.setVisibility(View.INVISIBLE);
            child.setDrawingCacheEnabled(true);
            Bitmap bitmap = child.getDrawingCache(true);
            bitmap = Bitmap.createBitmap(bitmap);
            child.setDrawingCacheEnabled(false);
            Paint paint = new Paint();
            paint.setAlpha(alpha);
            canvas.drawBitmap(bitmap, 0, 0, paint);
        }
    }
}