android仿京东搜索框,仿京东滑动页面搜索框背景渐变实现方法

这里主要的两个控件就是 Linelayout(包裹的是搜索框部分) Scrollview(包裹的滑动整体页面)

提醒(一定要用RelativeLayout布局)

设置控件在布局最上边line.bringToFront();//相当于改变Z轴

好了直接上代码

第一步:定义控件

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

}

}

}

定义控件添加监听方法

第二步:布局

scrollview默认只有一个子空间,所以要添加一个布局进行包裹,内容自己加

第三步:Activity.class

public class MainActivity extends AppCompatActivity {

private LinearLayout line;

private ObservableScrollView scrollView;

private int imageHeight=300; //设置渐变高度,一般为导航图片高度,自己控制

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

//查找控件

line= (LinearLayout) findViewById(R.id.line);

scrollView= (ObservableScrollView) findViewById(R.id.scrollView);

//搜索框在布局最上面

line.bringToFront();

//滑动监听

scrollView.setScrollViewListener(new ObservableScrollView.ScrollViewListener() {

@Override

public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {

if (y <= 0) {

line.setBackgroundColor(Color.argb((int) 0, 227, 29, 26));//AGB由相关工具获得,或者美工提供

} else if (y > 0 && y <= imageHeight) {

float scale = (float) y / imageHeight;

float alpha = (255 * scale);

// 只是layout背景透明

line.setBackgroundColor(Color.argb((int) alpha, 227, 29, 26));

} else {

line.setBackgroundColor(Color.argb((int) 255, 227, 29, 26));

}

}

});

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值