Design Support Library是在Google I/O2015上发布的一个全新兼容函数库,主要包括:
CoordinatorLayout继承ViewGroup,是Design Support Library中的布局,可以使不同视图组件直接相互作用,并协调动画效果。
看如下效果对比:
右图使用的是CoordinatorLayout,可以看出动画效果要比左图更和谐。
布局文件代码:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.tlkg.welcome.coordinatorlayoutdemo.MainActivity">
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|right|end"
android:layout_margin="16dp"
android:src="@mipmap/ic_launcher_round" />
</android.support.design.widget.CoordinatorLayout>
MainActivity代码:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Snackbar.make(v, "Hello", Snackbar.LENGTH_SHORT).show();
}
});
}
}
在CoordinatorLayout有一个onStartNestedScroll方法
@Override
public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) {
boolean handled = false;
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View view = getChildAt(i);
if (view.getVisibility() == View.GONE) {
// If it's GONE, don't dispatch
continue;
}
final LayoutParams lp = (LayoutParams) view.getLayoutParams();
final Behavior viewBehavior = lp.getBehavior();
if (viewBehavior != null) {
final boolean accepted = viewBehavior.onStartNestedScroll(this, view, child, target,
nestedScrollAxes);
handled |= accepted;
lp.acceptNestedScroll(accepted);
} else {
lp.acceptNestedScroll(false);
}
}
return handled;
}
会遍历子View,如果childView隐藏,跳过,获取Behavior对象,Behavior继承自View,调用Behavior对象的onStartNestedScroll方法来实现scroll效果,有兴趣的可以看下源码。