一,common_change_color - 渐变背景色
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
android:angle="0"
android:centerX="0.5"
android:centerY="0.5"
android:endColor="#FF6461"
android:startColor="#ff9b78"
android:type="linear" />
</shape>
二,MyScrollView - 主要获取y轴的滑动距离
package com.example.thinkpad.demo2.ui;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ScrollView;
public class MyScrollViewextends ScrollView {
private OnScrollListenerlistener;
public void setOnScrollListener(OnScrollListener listener) {
this.listener = listener;
}
public MyScrollView(Context context) {
super(context);
}
public MyScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
//设置接口
public interface OnScrollListener{
void onScroll(int scrollY);
}
//重写原生onScrollChanged方法,将参数传递给接口,由接口传递出去
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
if(listener !=null){
//这里我只传了垂直滑动的距离
listener.onScroll(t);
}
}
}
MainActivity - 逻辑
package com.example.thinkpad.demo2.activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.example.thinkpad.demo2.R;
import com.example.thinkpad.demo2.ui.MyScrollView;
public class MainActivityextends AppCompatActivity {
private RelativeLayoutlayoutTitle;
private TextViewtvTitle;
private MyScrollViewscrollView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
scrollView = findViewById(R.id.scrollView);
layoutTitle = findViewById(R.id.rl_title);
tvTitle = findViewById(R.id.tv_title);
//初始化的时候先行隐藏
tvTitle.setVisibility(View.GONE);
layoutTitle.getBackground().setAlpha(0);
//通过上下滑动的距离,动态设置title背景色的透明度 与 title的显示状态
scrollView.setOnScrollListener(new MyScrollView.OnScrollListener() {
@Override
public void onScroll(int scrollY) {
if (0 < scrollY && scrollY <=255) {
tvTitle.setVisibility(scrollY >50 ? View.VISIBLE : View.GONE);
layoutTitle.getBackground().setAlpha(scrollY);
}else if (scrollY >255) {
tvTitle.setVisibility(View.VISIBLE);
layoutTitle.getBackground().setAlpha(255);
}else {
tvTitle.setVisibility(View.GONE);
layoutTitle.getBackground().setAlpha(0);
}
}
});
}
}