您的位置:首页 > 其它

一个简单的仿京东搜索框背景渐变

2016-12-02 17:39 337 查看
1、首先自定义一个scollview

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);
}
}


2、在Activity里实现接口并监听滑动距离设置透明度

public class MainActivity extends Activity implements ObservableScrollView.ScrollViewListener{
LinearLayout linear;
ObservableScrollView  scroll;
GradientDrawable grad;//这里我们使用一个shape指向的类可以实现shape的各种效果
@Override
protected void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linear=(LinearLayout) findViewById(R.id.m_home_search);
scroll=(ObservableScrollView) findViewById(R.id.m_home_scroll);
scroll.setScrollViewListener(this);
grad=new GradientDrawable();
float scale2 = (float) 150 / 350;
float alpha2 = (255 * scale2);
grad.setColor(Color.argb((int) alpha2, 204, 204, 204)); //初始化透明度为完全透明
grad.setCornerRadius(45);
linear.setBackground(grad);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public void onScrollChanged(ObservableScrollView scrollView, int x, int y,
int oldx, int oldy) {
if(y<=0){
grad.setColor(Color.argb((int)0, 240, 240, 240)); //Y轴0点的时候完全透明
linear.setBackground(grad);
}else if(y > 100 && y <= 350){ //我们假设轮播图的高度为350
float scale = (float) y / 350;
float alpha = (255 * scale);
grad.setColor(Color.argb((int) alpha, 240, 240, 240));
linear.setBackground(grad);
}
}

}




xml代码就不在这里提供了 下面附上demo

如果你觉得这篇文章对你有用,那么赞一个或者留个言吧~

源码点击下载
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  标题栏背景渐变