按规矩办事,先看一下效果图
图三为ScllorView滚动下来的状态
public class MainActivity extends AppCompatActivity {
private TextView mTitleBarMain;
private ScrollView mScrollViewMain;
private int height;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initListener();
}
private void initView() {
mTitleBarMain = findViewById(R.id.main_titleBar);
mScrollViewMain = findViewById(R.id.main_scrollView);
}
@RequiresApi(api = Build.VERSION_CODES.M)
private void initListener() {
mScrollViewMain.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
height = mTitleBarMain.getHeight()*2;
}
});
mScrollViewMain.setOnScrollChangeListener(new View.OnScrollChangeListener() {
@Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
// TODO Auto-generated method stub
if (scrollY <= 0) { //设置标题的背景颜色
mTitleBarMain.setTextColor(Color.argb((int) 0, 0,0,0));
mTitleBarMain.setBackgroundColor(Color.argb((int) 255, 255, 255, 255));
} else if (scrollY > 0 && scrollY <= height) {
//滑动距离小于图片的高度时,设置背景和字体颜色颜色透明度渐变
float scale = (float) scrollY / height;
float alpha = (255 * scale);
mTitleBarMain.setTextColor(Color.argb((int) alpha, 255,255,255));
mTitleBarMain.setBackgroundColor(Color.argb((int) alpha, 0, 0, 0));
} else { //滑动到图片下面设置普通颜色
mTitleBarMain.setBackgroundColor(Color.argb((int) 255, 0, 0, 0));
}
}
});
}
}
1.获取到TitleBar的高度。
2.通过监听scrollY判断ScrollView Y轴滑动的位置。
3.如果scrollY为0的时候就代表ScrollView没有滑动,那么就给TitleBar设置白色背景和黑色字体。
4.如果scrollY不为0而且小于TitleBar高度的时候,将背景和字体颜色设置为渐变。
5.其他情况下(也就是说滑动高度大于TitleBar的时候)将TitleBar设置黑色背景和白色字体。
private void initListener() {
mScrollViewMain.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
height = mTitleBarMain.getHeight()*2;
}
});
mScrollViewMain.setOnScrollChangeListener(new View.OnScrollChangeListener() {
@Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
// TODO Auto-generated method stub
if (scrollY <= 0) { //设置标题的背景颜色
mTitleBarMain.setTextColor(Color.argb((int) 0, 0,0,0));
mTitleBarMain.setBackgroundColor(Color.argb((int) 255, 255, 255, 255));
} else if (scrollY > 0 && scrollY <= height) {
//滑动距离小于图片的高度时,设置背景和字体颜色颜色透明度渐变
float scale = (float) scrollY / height;
float alpha = (255 * scale);
mTitleBarMain.setTextColor(Color.argb((int) alpha, 255,255,255));
mTitleBarMain.setBackgroundColor(Color.argb((int) alpha, 0, 0, 0));
} else { //滑动到图片下面设置普通颜色
mTitleBarMain.setBackgroundColor(Color.argb((int) 255, 0, 0, 0));
}
}
});
}