android:clipToPadding属性应用
效果如下
效果实现是非常简单的,只需要自定义scrollview的滑动监听,动态设置toolbar的透明度即可。
代码如下
- XML布局
```java
- 自定义scrollview滑动监听
```java
public class MyScrollView extends ScrollView {
private OnScrollChangedListener listener;
private int heightPixels;
public MyScrollView(Context context) {
this(context,null);
}
public MyScrollView(Context context, AttributeSet attrs) {
this(context, attrs,0);
}
public MyScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
//获取屏幕高度
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
heightPixels = metrics.heightPixels;
}
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
if (listener!=null) {
//滑动的高度小于等于
int scrollY = getScrollY();
if(scrollY<=heightPixels/3f){
listener.change(1-scrollY/(heightPixels/3f));
}
}
}
public interface OnScrollChangedListener{
/*
alpha 1-0;
*/
void change(float alpha);
}
public void setOnScrollChangedListener(OnScrollChangedListener listener){
this.listener = listener;
}
}
- activity中修改toolbar的透明度
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
MyScrollView scrollView= (MyScrollView) findViewById(R.id.scrollView);
scrollView.setOnScrollChangedListener(this);
}
public void change(float alpha) {
toolbar.setAlpha(alpha);
}
运行发现,toolbar虽然成功的变淡,但是白了块,和我们的的目标效果并不一样。
解决的方法有很多中,这里介绍一种非常简单的方式
clipToPadding
clipToPadding是ViewGroup中的一个属性,默认为true
case R.styleable.ViewGroup_clipToPadding:
setClipToPadding(a.getBoolean(attr, true));
/**
* Sets whether this ViewGroup will clip its children to its padding and resize (but not
* clip) any EdgeEffect to the padded region, if padding is present.
* <p>
* By default, children are clipped to the padding of their parent
* ViewGroup. This clipping behavior is only enabled if padding is non-zero.
*
* @param clipToPadding true to clip children to the padding of the group, and resize (but
* not clip) any EdgeEffect to the padded region. False otherwise.
* @attr ref android.R.styleable#ViewGroup_clipToPadding
*/
public void setClipToPadding(boolean clipToPadding) {
if (hasBooleanFlag(FLAG_CLIP_TO_PADDING) != clipToPadding) {
setBooleanFlag(FLAG_CLIP_TO_PADDING, clipToPadding);
invalidate(true);
}
}
什么意思呢? 就是说clipToPadding属性定义了是否允许ViewGroup在padding中绘制,该值默认为true,即不允许,false则刚好相反。
那我们改一下布局文件
<livesun.letterindex.ui.MyScrollView
android:id="@+id/scrollView"
android:clipToPadding="false"
android:paddingTop="?actionBarSize"
android:layout_width="match_parent"
android:layout_height="match_parent">
当然 listview 和 recycleview 也同样适用 可以自己试试哦。