我有一个不动的imageView和一个水平的recyclerView。
当recyclerview的项目在imageview的后面时,我想获取该项目的位置。但为此滚动4或5个项目后,我得到的力却关闭了:
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getLeft()' on a null object reference
我正在使用
findFirstCompletelyVisibleItemPosition()
findLastCompletelyVisibleItemPosition()
所以我对为什么我的对象为null感到困惑。
代码:
final View view_emp = (View) findViewById(R.id.view_empty);
recycler_p.setOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
from_recycler_or_pager=2;
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (from_recycler_or_pager !=4) {
int firstPos = horizontalLayoutManager.findFirstCompletelyVisibleItemPosition();
int lastPos = horizontalLayoutManager.findLastCompletelyVisibleItemPosition();
}
for (int i = firstPos; i <= lastPos; i++) {
boolean bool = CheckCollision(view_emp, horizontalLayoutManager.getChildAt(i));
if (bool == true) {
Log.d("boooooool : ", "true" + String.valueOf(i));
}
}
}
public boolean CheckCollision(View v1,View v2) {
float x1 = v1.getLeft();
float x2 = v2.getLeft();
if ( x2 >= x1-20 && x2 <= x1+20){
return true;
}
return false;
}
还有另一件事
我的目标方式正确吗?