第一步:导入自定义ScrollView的类 ObservableScrollView.Java
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ScrollView;
/**
* 带滚动监听的scrollview
*
*/
public class ObservableScrollView extends ScrollView {
public interface ScrollViewListener {
void onScrollChanged(ObservableScrollView scrollView, int x, int y,
int oldx, int oldy);
}
private ScrollViewListener scrollViewListener = null;
public ObservableScrollView(Context context) {
super(context);
}
public ObservableScrollView(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
public ObservableScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setScrollViewListener(ScrollViewListener scrollViewListener) {
this.scrollViewListener = scrollViewListener;
}
@Override
protected void onScrollChanged(int x, int y, int oldx, int oldy) {
super.onScrollChanged(x, y, oldx, oldy);
if (scrollViewListener != null) {
scrollViewListener.onScrollChanged(this, x, y, oldx, oldy);
}
}
}
第二步 界面文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<cn.hwwwwh.cn.ObservableScrollView
android:id="@+id/scrollview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="@+id/imageview"
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="@drawable/zuqiu" />
</LinearLayout>
</cn.hwwwwh.cn.ObservableScrollView>
<TextView
android:id="@+id/textview"
android:layout_width="match_parent"
android:layout_height="48dp"
android:gravity="center"
android:text="标题"
android:textSize="18sp"
android:textColor="@android:color/white"
android:background="#00000000" />
</RelativeLayout>
第三步 源代码调用以下两个方法
private void initListeners() {
// 获取顶部图片高度后,设置滚动监听
ViewTreeObserver vto = imageView.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
imageView.getViewTreeObserver().removeGlobalOnLayoutListener(
this);
imageHeight = imageView.getHeight();
scrollView.setScrollViewListener(MainActivity.this);
}
});
}
@Override
public void onScrollChanged(ObservableScrollView scrollView, int x, int y,
int oldx, int oldy) {
// TODO Auto-generated method stub
// Log.i("TAG", "y--->" + y + " height-->" + height);
if (y <= 0) {
textView.setBackgroundColor(Color.argb((int) 0, 227, 29, 26));//第一个参数0表示透明度范围是0~255,后面为RGB参数
} else if (y > 0 && y <= imageHeight) {
float scale = (float) y / imageHeight;
float alpha = (255 * scale);
textView.setBackgroundColor(Color.argb((int) alpha, 227, 29, 26));
} else {
textView.setBackgroundColor(Color.argb((int) 255, 227, 29, 26));
}
}
}
到这里应该就可以实现,具体参数根据实际调整