Android 图片渐变切换效果


package com.example.xyz.colorchange;


import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;


public class MainActivity extends AppCompatActivity {


    private Drawable oldBackground = null;


    private Drawable bg_a;
    private Drawable bg_b;
    LinearLayout up;
    int isWhat=1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        up =(LinearLayout) findViewById(R.id.up);


        up.setBackgroundResource(R.mipmap.a);


        bg_a = getResources().getDrawable(R.mipmap.a);
        bg_b =getResources().getDrawable(R.mipmap.b);


       


        up.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(isWhat==1)
                    aTob();
                else if(isWhat==2)
                    bToa();
            }
        });
    }






    private void aTob() {
        up.setBackgroundResource(R.mipmap.a);
        //渐变切换
        TransitionDrawable td = new TransitionDrawable(new Drawable[]{bg_a, bg_b});
        up.setBackgroundDrawable(td);
        td.startTransition(1000);
        isWhat=2;
    }




    private void bToa() {
        up.setBackgroundResource(R.mipmap.b);
        //渐变切换
        TransitionDrawable td = new TransitionDrawable(new Drawable[]{bg_b, bg_a});
        up.setBackgroundDrawable(td);
        td.startTransition(1000);
        isWhat=1;
    }
}



假如需要 从透明渐变切换到特定背景的话 可以这样写

td = new TransitionDrawable(new Drawable[]{getResources().getDrawable(android.R.color.transparent),bg_on});

反之,把transitionDrawable数组中元素反过来即可.


github :  https://github.com/Cedric-Xuan/colorChange

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值