Android 监听ScrollView滑动 实现布局背景、文本颜色渐变

    在浏览App页面的时候,发现随着页面上下滑动,上面导航栏的背景颜色和TextView文字逐渐发生变化,这种效果非常多,开始感觉很神奇,查阅相关资料后,发现实现起来还是比较简单的,现实现过程如下:

一、activity_main.xml文件中




    
    

    

     

    

    
    
    
    
    
    



   
      
   


二、MainActivity.java中

public class MainActivity extends AppCompatActivity {
    //滑动布局ScrollView
    private ScrollView mScrollView;
    private TextView tv01,tv02,tvTitle;
    //标题栏布局LinearLayout
    private LinearLayout mLinearLayout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        setOnClickListener();
    }
    private void initView() {
        mScrollView = (ScrollView) findViewById(R.id.scrollView);
        tv01 = (TextView) findViewById(R.id.tv01);
        tv02 = (TextView) findViewById(R.id.tv02);
        tvTitle = (TextView) findViewById(R.id.tv_title);
        mLinearLayout = (LinearLayout) findViewById(R.id.line_title);
    }
    @TargetApi(Build.VERSION_CODES.M)
    private void setOnClickListener() {
        //mScrollView滑动监听
        mScrollView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                tvTitle.setText(R.string.title);
                //获取tv01、tv01控件的高度
                int height = tv01.getMeasuredHeight()+tv02.getMeasuredHeight();
                if (scrollY <= 0){
                    //滑动之前,标题栏布局背景颜色为完全透明,标题文字完全透明
                    mLinearLayout.setBackgroundColor(Color.argb(0,0,0,0));
                    tvTitle.setTextColor(Color.argb(0,255,255,255));
                    //让mScrollView滑动的距离在0~height之间时颜色发生渐变
                }else if(scrollY >0 && scrollY <= height){
                    //获取渐变率
                    float scale = (float) scrollY / height;
                    //获取渐变数值
                    float alpha = (255 * scale);
                    //布局文本颜色逐渐发生变化
                    mLinearLayout.setBackgroundColor(Color.argb((int) alpha,0,0,0));
                    tvTitle.setTextColor(Color.argb((int) alpha,255,255,255));
                }else {
                    //当滑动距离超过height,布局文本颜色完全不透明
                    mLinearLayout.setBackgroundColor(Color.argb(255,0,0,0));
                    tvTitle.setTextColor(Color.argb(255,255,255,255));
                }
            }
        });
    }
}

运行效果如下:




以上是以ScrollView为例,其它如ListView、RecycleView等实现方法类似。




你可能感兴趣的:(Android 监听ScrollView滑动 实现布局背景、文本颜色渐变)