我尝试了很多代码,以给出更多或少你所寻找的东西。这是一种替代方案,但你需要将AppBarLayout更改为简单视图...看看这个:
<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:id="@+id/annonce.main.coordinator"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:ignore="RtlHardcoded">
<android.support.v7.widget.RecyclerView
android:id="@+id/rv"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<android.support.v7.widget.CardView
android:id="@+id/searchbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardElevation="4dp"
app:cardUseCompatPadding="true"
app:layout_behavior="[package].RecyclerSearchBehavior">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:hint="Pesquise aqui"
android:minHeight="58dp"/>
</android.support.v7.widget.CardView>
注意:这是在CoordinatorLayout内部。
创建一个Behavior,其中视图是您正在使用的搜索栏的类型:
public class RecyclerSearchBehavior extends CoordinatorLayout.Behavior<CardView> {
private int mViewHeight;
private int[] mViewStartLocation;
public RecyclerSearchBehavior(Context context, AttributeSet attrs) {
}
@Override
public boolean layoutDependsOn(CoordinatorLayout parent, final CardView child, View dependency) {
mViewHeight = child.getHeight();
mViewStartLocation = new int[2];
child.getLocationOnScreen(mViewStartLocation);
if (dependency instanceof RecyclerView)
((RecyclerView) dependency).addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
animate(child, dy);
}
});
return dependency instanceof RecyclerView;
}
private void animate(CardView child, int dy) {
if (child.getY() <= 0)
if (dy >= 0) {
if ((child.getY() * -1) <= (mViewHeight))
child.setTranslationY(child.getY() - dy * 0.1f);
} else {
if (child.getY() < 0)
child.setTranslationY(child.getY() - dy * 0.1f);
else child.setY(0);
}
else child.setY(0);
}
}
完成了。你的“搜索栏”已经在这里。
唯一的问题是,你需要给Recycler的第一个项目添加填充,或者作为第一个项目的透明视图。
AppbarLayout
和NestedScrollView
中添加android:fitsSystemWindows="true"
。 - jayeshsolanki93