第一步: 导入相应的design包
1 dependencies { 2 ...... 3 implementation 'com.android.support:design:27.1.0' 4 }
第二步:布局文件
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 xmlns:app="http://schemas.android.com/apk/res-auto" 6 android:background="#EFF3F7" 7 tools:context=".MainActivity" 8 android:orientation="vertical"> 9 10 <android.support.design.widget.CoordinatorLayout 11 android:layout_width="match_parent" 12 android:layout_height="wrap_content"> 13 14 <android.support.design.widget.AppBarLayout 15 android:layout_width="match_parent" 16 android:layout_height="200dp" 17 app:layout_behavior="com.sun.testpopu.FixAppBarLayout" 18 app:elevation="0dp"> 19 20 <View 21 android:layout_width="match_parent" 22 android:layout_height="200dp" 23 android:background="#000000" 24 app:layout_scrollFlags="scroll|enterAlwaysCollapsed"/> 25 </android.support.design.widget.AppBarLayout> 26 <android.support.v7.widget.RecyclerView 27 android:layout_width="match_parent" 28 android:layout_height="1000dp" 29 app:layout_behavior="@string/appbar_scrolling_view_behavior"/> 30 </android.support.design.widget.CoordinatorLayout> 31 </LinearLayout>
第二步:解决滑动抖动问题
1 /** 2 * @author Sigal 3 * on 2018/11/26 4 * note: 解决AppBarLayout滑动时抖动问题 5 */ 6 public class FixAppBarLayout extends AppBarLayout.Behavior { 7 private static final String TAG = "AppBarLayoutBehavior"; 8 9 public FixAppBarLayout() { 10 super(); 11 } 12 13 public FixAppBarLayout(Context context, AttributeSet attrs) { 14 super(context, attrs); 15 } 16 17 @Override 18 public boolean onInterceptTouchEvent(CoordinatorLayout parent, AppBarLayout child, MotionEvent ev) { 19 if (ev.getAction() == ACTION_DOWN) { 20 Object scroller = getSuperSuperField(this, "mScroller"); 21 if (scroller != null && scroller instanceof OverScroller) { 22 OverScroller overScroller = (OverScroller) scroller; 23 overScroller.abortAnimation(); 24 } 25 } 26 27 return super.onInterceptTouchEvent(parent, child, ev); 28 } 29 30 private Object getSuperSuperField(Object paramClass, String paramString) { 31 Field field = null; 32 Object object = null; 33 try { 34 field = paramClass.getClass().getSuperclass().getSuperclass().getDeclaredField(paramString); 35 field.setAccessible(true); 36 object = field.get(paramClass); 37 } catch (Exception e) { 38 e.printStackTrace(); 39 } 40 return object; 41 } 42 }
注:在布局文件中引用:app:layout_behavior="com.sun.testpopu.FixAppBarLayout"