Android实现滑动布局使TitleBar文本渐变色

来源:互联网 发布:socket 的类型 知乎 编辑:程序博客网 时间:2024/05/16 18:58

原理

想要实现渐变的效果,就需要知道ViewTreeObserver:它是一个注册监听视图树的观察者(observer),在视图树种全局事件改变时得到通知。这个全局事件不仅还包括整个树的布局,从绘画过程开始,触摸模式的改变等。ViewTreeObserver不能够被应用程序实例化,因为它是由视图提供。它的实现接口有以下几个:1、当在一个视图树中的焦点状态发生改变时,所要调用的回调函数的接口类。interface  ViewTreeObserver.OnGlobalFocusChangeListener2、当在一个视图树中全局布局发生改变或者视图树中的某个视图的可视状态发生改变时,所要调用的回调函数的接口类。interface  ViewTreeObserver.OnGlobalLayoutListener3、当一个视图树将要绘制时,所要调用的回调函数的接口类。interface  ViewTreeObserver.OnPreDrawListener4、当一个视图树中的一些组件发生滚动时,所要调用的回调函数的接口类。interface  ViewTreeObserver.OnScrollChangedListener5、当一个视图树的触摸模式发生改变时,所要调用的回调函数的接口类。interface  ViewTreeObserver.OnTouchModeChangeListener

实现

而我们想要实现的效果是当用户首次进入类似淘宝商品名称的显示,我们并不想让用户看到名称在最顶端,直接显示大图,当用户向上滑动时,再开始渐变色的显示出来名称等内容。那么可以从上述接口中看到第二个接口恰好符合要求。1、首先需要自定义一个ScrollView或者直接使用获取的ScrollView实现其滚动接口。onScrllChanged(int x,int y,int oldX,int oldY);2、在这个ScrollView中我们是依据哪个布局为基准进行title的渐变显示和隐藏,我们就获取该控件3、获取该控件的视图数,以ImageView基准为例 ViewTreeObserver treeObserver = imageView.getViewTreeObserver(); treeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {        @Override        public void onGlobalLayout() {            ivObserver.getViewTreeObserver().removeOnGlobalLayoutListener(this);            //获取imageView的高度,为什么不直接获取呢?如果在代码中直接获取你会发现返回值为0。            height = ivObserver.getHeight();            scrollView.setOnScrollChangeListener(TestPayActivity.this);        }    });4、在此接口中进行设置alpha值即可控制显示效果了 @Overrideprotected void onScrollChanged(int x, int y, int oldx, int oldy) {    super.onScrollChanged(x, y, oldx, oldy);    if (y <= 0) {        view.setVisibility(VISIBLE);        if (view instanceof TextView) {            ((TextView) view).setText("");            ((TextView) view).setTextColor(Color.argb(0, 0, 0, 0));        }        view.setBackgroundColor(Color.argb(0, 255, 255, 255));    } else if (y > 0 && y < observerHeight) {        float factor = (float) y / observerHeight;        int alpha = (int) (factor * 255);        view.setVisibility(View.VISIBLE);        if (view instanceof TextView) {            ((TextView) view).setTextColor(Color.argb(alpha, 0, 0, 0));            ((TextView) view).setText(tvTitle);        }        viewGroup.setBackgroundColor(Color.argb(alpha, 255, 255, 255));    } else {        view.setVisibility(View.VISIBLE);        if (view instanceof TextView) {            ((TextView) view).setTextColor(Color.BLACK);            ((TextView) view).setText(tvTitle);        }        viewGroup.setBackgroundColor(Color.WHITE);    }}
原创粉丝点击