简体   繁体   English

滚动Listview并停在任何项目时,它将移至android的最高位置

[英]When scrolling Listview and stops at any item, it moves to top position android

I am getting items based on pagination.All items are displaying but problem is that when i stop scrolling at any position, it moves to top. 我正在获取基于分页的项目。所有项目都在显示,但是问题是当我停止在任何位置滚动时,它都会移到顶部。 Please help me to solve this. 请帮我解决这个问题。 I have issue in onscrolllistener in listview . 我在listview onscrolllistener中遇到问题。

My code is as follows: 我的代码如下:

int pagesize = 1;

private class MovieTop extends AsyncTask {

@Override
protected ArrayList<HashMap<String, String>> doInBackground(
        Object... params) {
    try {
        return displayTopMovies();
    } catch (IOException e) {
        return null;
    }
}


public ArrayList<HashMap<String, String>> displayTopMovies()
        throws IOException {

    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder
            .append("https://movie.org/movie/popular?");
    stringBuilder.append("?api_key=" + "c68"+"&&page="+pagesize); //getting page increment
    URL url = new URL(stringBuilder.toString());
    InputStream stream = null;
    try {
        // Establish a connection
        HttpURLConnection conn = (HttpURLConnection) url
                .openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.addRequestProperty("Accept", "application/json");              conn.setDoInput(true);
        conn.connect();
        int responseCode = conn.getResponseCode();
        Log.d(DEBUG_TAG, "The response code is: " + responseCode + " "
                + conn.getResponseMessage());

        stream = conn.getInputStream();
        return parseTopMovies(stringify(stream));
    } finally {
        if (stream != null) {
            stream.close();
        }
    }
}
  parsing been done here..
private ArrayList<HashMap<String, String>> parseTopMovies(String result) {
    String streamAsString = result;
    ArrayList<HashMap<String, String>> results = new ArrayList<HashMap<String, String>>();
    try {
        JSONObject jsonObject = new JSONObject(streamAsString);
        JSONArray array = (JSONArray) jsonObject.get("results");
        for (int i = 0; i < array.length(); i++) {
            HashMap<String, String> map = new HashMap<String, String>();
            JSONObject jsonMovieObject = array.getJSONObject(i);
            map.put(KEY_TITLE,
                    jsonMovieObject.getString("original_title"));
            results.add(map);
        }
    } catch (JSONException e) {
        System.err.println(e);
        Log.d(DEBUG_TAG, "Error parsing JSON. String was: "
                + streamAsString);
    }
    return results;
}

}
   @Override
  protected void onPostExecute(Object result) {
    update2((ArrayList<HashMap<String, String>>) result);
    };


   //Here i am displaying result
   public void update2(ArrayList<HashMap<String, String>> result) {
   this.result.addAll(result);
   ListView listView =(ListView)findViewById(R.id.container);

   // Add results to listView.
   adapter = new UpcomingMovieAdapters(this, R.layout.upcoming,result);
   listView.setAdapter(adapter);
   // here i am using notifyDatasetchanged.
   adapter.notifyDataSetChanged();
    try {

        listView.setOnScrollListener(new OnScrollListener() {
            public void onScroll(AbsListView view, int firstVisibleItem,
                    int visibleItemCount, int totalItemCount) {

                // TODO Auto-generated method stub
            }

            public void onScrollStateChanged(AbsListView view,
                    int scrollState) {
                // TODO Auto-generated method stub
                if (scrollState == 0) {
                    // Log.i("a", "scrolling stopped...");
                    if (pagesize <= 30) {
          Toast.makeText(getApplicationContext(),"Moving to top when scroll stopped at any item position..", 1000).show();
                        pagesize = pagesize + 1;

                            new MovieTop().execute();
                    }
                }
            }

        });
    } catch (Exception e) {
        System.out.println(e);
    }

}

as you create Adapter in each incoming data, your list scroll to first position, for handling this issue you need create your adapter just once then use adapter.notifyDataSetChanged(); 在每个传入数据中创建适配器时,列表将滚动到第一个位置,要处理此问题,您只需创建适配器一次,然后使用adapter.notifyDataSetChanged(); for refreshing data. 用于刷新数据。

in onCreate method use onCreate方法中使用

 adapter = new UpcomingMovieAdapters(this, R.layout.upcoming,result);
 listView.setAdapter(adapter);

then in async class use following code. 然后在异步类中使用以下代码。

 public void update2(ArrayList<HashMap<String, String>> result) {
   this.result.addAll(result);

   // just use this line 
   adapter.notifyDataSetChanged();

The problem is you're setting the adapter to the list repeatedly. 问题是您反复将适配器设置为列表。 You should only do this once, every time you set it the list view is reset to the top. 每次设置后,您只应该执行一次,列表视图将重置为顶部。 Instead you need to have one instance of the adapter to update then call notifyDataSetChanged() to tell the list view to update itself. 相反,您需要具有一个适配器实例来进行更新,然后调用notifyDataSetChanged()来通知列表视图进行自身更新。

I think, that problem is in calling new MovieTop().execute(); 我认为,问题出在调用new MovieTop().execute(); onScroll stopped, because data are parsed for next page, but Adapter is created again in onPostExecute . onScroll已停止,因为已为下一页解析了数据,但是在onPostExecute再次创建了onPostExecute

If this.result is ArrayList with all results, try to use: 如果this.result是具有所有结果的ArrayList,请尝试使用:

if(adapter == null) {
    adapter = new UpcomingMovieAdapters(this, R.layout.upcoming,result);
    listView.setAdapter(adapter);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM