您的位置:首页 > 移动开发 > Android开发

Android ScrollView滑动标题栏变色

2016-12-13 18:44 447 查看
就不上效果图了,现在各种app都有这种效果,随着ScrollView的滑动,以某个View为参照,标题栏背景渐渐由 透明 -> 指定颜色

很多实现方法,以下为重写ScrollView。

布局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<AlphaTitleScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-各种内容->
</LinearLayout>

</AlphaTitleScrollView>

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="标题"/>
</RelativeLayout>

重写的ScrollView:

public class AlphaTitleScrollView extends ScrollView {

private View mReferenceView;
private View mTitleView;
private int backgroundColor;
private int[] backgroundColorRGB;
private boolean isSlowlyChange = true;

public AlphaTitleScrollView(Context context) {
super(context);
}

public AlphaTitleScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}

public AlphaTitleScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public AlphaTitleScrollView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}

@Override
public void scrollTo(int x, int y) {
if (x == 0 && y == 0 || y <= 0) {
super.scrollTo(x, y);
}
}

public void setSlowlyChange(boolean slowlyChange) {
this.isSlowlyChange = slowlyChange;
}

/**
* 初始化设置参数
*
* @param titleView
* @param referenceView
* @param backgroundColor
* @param backgroundColorRGB
*/
public void initAlphaTitle(View titleView, View referenceView, int backgroundColor, int[] backgroundColorRGB) {
this.mTitleView = titleView;
this.mReferenceView = referenceView;
this.backgroundColor = backgroundColor;
this.backgroundColorRGB = backgroundColorRGB;
}

@Override
protected void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY) {
super.onOverScrolled(scrollX, scrollY, clampedX, clampedY);

if (scrollY >= mReferenceView.getTop() + mReferenceView.getMeasuredHeight()) {
mTitleView.setBackgroundColor(backgroundColor);
} else if (scrollY >= 0) {
if (!isSlowlyChange) {
mTitleView.setBackgroundColor(Color.TRANSPARENT);
} else {
float persent = scrollY * 1f / (mReferenceView.getTop() + mReferenceView.getMeasuredHeight());
int alpha = (int) (255 * persent);
int color = Color.argb(alpha, backgroundColorRGB[0], backgroundColorRGB[1], backgroundColorRGB[2]);
mTitleView.setBackgroundColor(color);
}
}

}

调用:

mAlphaScrollView.initAlphaTitle(titleView, headView, getResources().getColor(R.color.yellow), new int[]{253, 215, 62});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: