我正在尝试实现一个Snackbar,当用户在RecyclerView上滚动时,它会显示和关闭。这是视图的.xml文件。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/activityFriendsList">
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/friendsRecyclerView"/>
</android.support.design.widget.CoordinatorLayout>
</RelativeLayout>
这也是应该完成工作的功能
Snackbar snackbar;
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
snackbar = Snackbar.make(activity, "Add new friend", Snackbar.LENGTH_INDEFINITE);
snackbar.show();
if (dy > 0) {
Log.i("Info", "Scrolling up");
if(snackBarIsShowing) {
snackBarIsShowing = false;
}
}
if (dy < 0){
Log.i("Info", "Scrolling down");
if(!snackBarIsShowing) {
snackBarIsShowing = true;
}
}
if (snackBarIsShowing) {
Log.i("Info", "Create new");
snackbar.dismiss();
} else {
Log.i("Info", "Dismiss the old one");
}
}
});
我认为现在的问题是,现在我并不想解雇合适的小吃店。 知道如何克服这个问题。
答案 0 :(得分:1)
尝试这个,我已经测试了它并且它正常工作。
RecyclerAdapter adapter;
RecyclerView recyclerView;
private Snackbar snackbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
snackbar = Snackbar.make(findViewById(android.R.id.content), "should disappear when scrolling!", Snackbar.LENGTH_LONG);
recyclerView = findViewById(R.id.recyclerView);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
adapter = new RecyclerAdapter(myList);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public final void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (!recyclerView.canScrollVertically(-1)) {
if (!snackbar.isShown())
snackbar.show();
} else if (!recyclerView.canScrollVertically(1)) {
if (snackbar.isShown())
snackbar.dismiss();
}
if (dy < 0) {
if (!snackbar.isShown())
snackbar.show();
} else if (dy > 0) {
if (snackbar.isShown())
snackbar.dismiss();
}
}
});
}
注意: canScrollVertically(int direction)
direction
int:负向检查向上滚动,向左检查向下滚动。请参阅文档here