加载更多数据后, GridView 回到顶部,我想让它在加载后从最后一项开始滚动。
我尝试使用 onScrollStateChanged
,并使其以 state == SCROLL_STATE_TOUCH_SCROLL
加载,但我遇到了同样的问题。
@Override
protected void onPostExecute(ArrayList<productDetails> AProducts) {
final ArrayList<productDetails> products = AProducts;
super.onPostExecute(products);
productAdapter = new productAdapter(category.this, productDetailsArr);
gridView.setAdapter(productAdapter);
productAdapter.notifyDataSetChanged();
if (products != null) {
gridView.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem + visibleItemCount >= totalItemCount) {
// End has been reached
limit = Integer.parseInt(((productDetails) (products.get(products.size() - 1))).getProductID());
// limit = Integer.parseInt(products.get(3).get(products.get(3).size() - 1));
if (flimit != limit) {
flimit = limit; //to stop using last element in fatching last products more than one time.
if (UtilityClass.isInternetAvailable(getApplicationContext())) {
new getProductsTask().execute(category);
} else {
Intent internet = new Intent(getBaseContext(), NointernetConnection.class);
startActivity(internet);
finish();
}
} else {
Log.d("FLimit", ">>" + "END");
}
} else {
progressDialog.dismiss();
}
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
}
});
}
}
最佳答案
首先,您不需要每次都在 onPostExecute 方法中创建适配器类(productAdapter)的新对象,并且每次数据更改或网络调用有新响应时都将适配器设置为 gridview。这会导致滚动 gridview到顶部位置。相反,您可以在适配器类中创建一个 setter 方法。
ArrayList <productDetails> productDetailsArr;
public void setProductDetailsArr(ArrayList<productDetails> productDetailsArr) {
this.productDetailsArr = productDetailsArr;
}
并在 onPostExecute 方法中写下以下代码以检查 adaper 是否为 null。如果为 null,则只需创建一个新实例。否则,您只需提供一个新数据集并调用 notifyDataSetChanged()。
if(productAdapter == null)
{
productAdapter = new productAdapter(category.this, productDetailsArr);
gridView.setAdapter(productAdapter);
}else{
productAdapter.setProductDetailsArr(productDetailsArr);
productAdapter.notifyDataSetChanged();
}
关于android - 有没有一种方法可以防止 gridview 在其适配器的数据发生更改时滚动到其顶部位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36279719/