【发布时间】:2018-10-08 08:32:44
【问题描述】:
我需要获取用户位置并将该位置的请求发送到服务器。我有一个 recyclerview 用于显示服务器的数据。要更新位置,我在主要活动的 onStart 中使用此代码,并希望在 recyclerview 的空闲状态下获取位置。现在我不知道如何实现位置监听器。
维护活动:
if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}else{
locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, 10000, 0, locationListener);
}
和:
public abstract class StoryPaginationScrollListener extends RecyclerView.OnScrollListener{
LinearLayoutManager layoutManager;
LocationListener locationListener;
Context context;
public StoryPaginationScrollListener(LinearLayoutManager layoutManager, LocationListener locationListener, Context context) {
this.layoutManager = layoutManager;
this.locationListener = locationListener;
this.context = context;
}
@Override
public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if(newState == SCROLL_STATE_IDLE){
}
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int visibleItemCount = layoutManager.getChildCount();
int totalItemCount = layoutManager.getItemCount();
int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
if (!isLoading() && !isLastPage()) {
}
if ((visibleItemCount + firstVisibleItemPosition) >= totalItemCount && firstVisibleItemPosition >= 0) {
loadMoreItems();
}
}
}
protected abstract void loadMoreItems();
public abstract int getTotalPageCount();
public abstract boolean isLastPage();
public abstract boolean isLoading();
}
在这种情况下需要一个位置:if(newState == SCROLL_STATE_IDLE) 并在 loadMoreItems() 中使用这个位置。
【问题讨论】:
-
也许你应该让你的
Activity实现LocationListener接口,即拥有onLocationChanged()方法并拥有一个始终存储最新接收到的位置的成员变量。然后你可以在StoryPaginationScrollListener中读取这个变量,假设它可以访问Activity。如果出现问题,Android Studio 将指导实现接口。并准备等待位置。尤其是第一个基于 GPS 的位置可能需要一段时间才能出现。基于网络(手机信号塔)的速度很快,但不太准确。 -
即使我在主要活动中使用 locationlistener 也可以在
StoryPaginationScrollListener中使用? -
不,它需要在任何一个中。当然,您可能更清楚在您的应用中哪个位置合适。但是由于获取位置是一个异步操作,我认为将侦听器放在 Activity 中并保存最新位置可能是有意义的,因此您可以在需要时从 Activity 中读取它并开始加载更多内容你的 RecyclerView 马上。
标签: android android-recyclerview locationlistener