在我的应用程序中显示和隐藏一些小部件我在这个网站上找到了以下代码,但是我无法在我的片段上实现它,例如:
public abstract class HidingScrollListener extends RecyclerView.OnScrollListener {
private static final int HIDE_THRESHOLD = 20;
private int mScrolledDistance = 0;
private boolean mControlsVisible = true;
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int firstVisibleItem = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
if (firstVisibleItem == 0) {
if(!mControlsVisible) {
onShow();
mControlsVisible = true;
}
} else {
if (mScrolledDistance > HIDE_THRESHOLD && mControlsVisible) {
onHide();
mControlsVisible = false;
mScrolledDistance = 0;
} else if (mScrolledDistance < -HIDE_THRESHOLD && !mControlsVisible) {
onShow();
mControlsVisible = true;
mScrolledDistance = 0;
}
}
if((mControlsVisible && dy>0) || (!mControlsVisible && dy<0)) {
mScrolledDistance += dy;
}
}
public abstract void onHide();
public abstract void onShow();
}
我的片段:
public class FragmentMarketDetail extends Fragment implements ObservableHorizontalScrollView.OnScrollListener {
private ScrollView scrollViewTest;
private Context context;
public static FragmentMarketDetail newInstance() {
FragmentMarketDetail fragmentFirst = new FragmentMarketDetail();
return fragmentFirst;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_online_categories, container, false);
scrollViewTest = (ScrollView) view.findViewById(R.id.scrollViewTest);
scrollViewTest.setOnScrollChangeListener(context);
return view;
}
@Override
public void onScrollChanged(ObservableHorizontalScrollView scrollView, int x, int y, int oldX, int oldY) {
Log.e("-----> onScrollChanged", x + "");
}
@Override
public void onEndScroll(ObservableHorizontalScrollView scrollView) {
Log.e("----->onEndScroll ", "");
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
context = activity;
}
}
我收到此行的错误:scrollViewTest.setOnScrollChangeListener(context);
答案 0 :(得分:9)
您无法在API23下直接将onScrollChangedListener设置为ScrollView。 但是你可以使用这个
scrollView.getViewTreeObserver().addOnScrollChangedListener(new OnScrollChangedListener() {
@Override
public void onScrollChanged() {
int scrollX = rootScrollView.getScrollX(); //for horizontalScrollView
int scrollY = rootScrollView.getScrollY(); //for verticalScrollView
//DO SOMETHING WITH THE SCROLL COORDINATES
}
});
请参阅onScrollListener for a ScrollView
scrollViewTest.setOnScrollChangeListener(context);
在上面一行中,您尝试将Context
设置为无法进行的侦听,因为Fragment
实现了ObservableHorizontalScrollView.OnScrollListener
您应该调用
scrollViewTest.setOnScrollChangeListener(this);