如何在api level 7(Android 2.1)中设置整个视图的alpha值

Mic*_*ine 4 transparency android transition alpha

我有一个任意的观点,我想在另一个视图之上淡入.在api level 11中,我看到有一个setAlpha,但是我支持api级别7.我没有遇到过一个简单的方法来执行此操作.如何在不弄乱每个组件的情况下为整个视图设置alpha?

slu*_*und 13

您应该能够使用API​​级别7的AlphaAnimation实现合理的效果.

    View v = findViewById(R.id.view2);

    AlphaAnimation aa = new AlphaAnimation(0f,1f);
    aa.setDuration(5000);
    v.startAnimation(aa);
Run Code Online (Sandbox Code Playgroud)


Mic*_*ine 5

使用AlphaAnimation对于大多数过渡来说都是一个很好的解决方案,如果我找不到一种方法来完成我想做的事情,肯定会对我有用,这涉及基于倾斜以渐变的方式在两个视图之间淡入淡出设备的角度.幸运的是我有!这是我采取的策略:我将视图包装在FrameLayout的自定义子类中,并实现onDraw.在那里,我将子视图捕获为位图,然后使用预期的alpha重新绘制位图.这是一些代码.当我清理干净时我会编辑,这只是概念的证明,但它就像一个魅力:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)