如何在列表视图中实现适当的滚动以实现片段活动的分页?

时间:2014-09-26 20:17:06

标签: android android-fragments pagination

我正在构建像techcrunch这样的应用程序。我以JSON格式从服务器获取数据,并在列表视图中显示数据,如文章标题,作者姓名和图像。当用户在列表视图中滚动更多文章时,我已经应用了分页方式。我的分页工作正常,但滚动功能存在问题,因为新的或新的数据加载滚动剂量不与数据对齐。为了更清楚地用简单的单词来澄清,当我实际向下滚动时,我的滚动条位于页面顶部,这是我的代码:

public class OneFragment extends Fragment {

public OneFragment(){}
private static final String TAG = OneFragment.class.getSimpleName();

// Movies json url
private static String URL = "http:url&page=1";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
int current_page = 1;
int mPreLast;
@Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    final View rootView = inflater.inflate(R.layout.swip, container, false);

    pDialog = new ProgressDialog(getActivity());
    pDialog.setMessage("Loading...");
    pDialog.show();
    pDialog.setCancelable(false);


    listView = (ListView) rootView.findViewById(R.id.list49);
    listView.setOnScrollListener(new AbsListView.OnScrollListener()
    {
        @Override
        public void onScrollStateChanged(AbsListView absListView, int i)
        {

        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
        {
            int lastItem = firstVisibleItem + visibleItemCount;
               if(lastItem == totalItemCount){
                   if (mPreLast != lastItem)
                   {
                       mPreLast = lastItem;
                       onStart();

                   }
            }
        }
    });

    listView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?>  adapterView, View view, int Position,
                long offset)  { 
            // TODO Auto-generated method stub
            Movie item = (Movie) adapter.getItem(Position);             
            Intent intent = new Intent(rootView.getContext(), SingleArticle.class);
            single.date = item.getDate();
            single.id = item.getId();


            startActivity(intent);


            }        
        });
    //pDialog = new ProgressDialog(this);
    // Showing progress dialog before making http request

    return rootView;
}

@Override
public void onStart(){
    super.onStart();
    // calling adapter changes here, just
    // to avoid getactivity()null
    // increment current page
    current_page += 1;

    // Next page request
    URL = "http:url&page=" + current_page;
    //adapter = new CustomListAdapter(this, movieList);

    // changing action bar color
    //getActivity().getActionBar().setBackground(
            //new ColorDrawable(Color.parseColor("#1b1b1b")));

    // Creating volley request obj
    JsonArrayRequest movieReq = new JsonArrayRequest(URL,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.d(TAG, response.toString());
                    hidePDialog();

                    // Parsing json
                    for (int i = 0; i < response.length(); i++) {
                        try {

                            JSONObject obj = response.getJSONObject(i);
                            Movie movie = new Movie();
                            movie.setDate(obj.getString("date"));
                            movie.setId(obj.getString("id"));

                            movieList.add(movie);
                            int currentPosition = listView.getFirstVisiblePosition();

                            adapter = new CustomListAdapter(getActivity(), movieList);
                            adapter.notifyDataSetChanged();

                            listView.setAdapter(adapter);
                            listView.setSelectionFromTop(currentPosition + 1, 0);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }                       
                }
            },new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d(TAG, "Error: " + error.getMessage());
                    new AlertDialog.Builder(getActivity())
                    .setTitle("No Connectivity ")
                    .setMessage("Please check your internet connectivity!")
                    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) { 
                            // continue with delete
                        }
                     })
                    //.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                        //public void onClick(DialogInterface dialog, int which) { 
                            // do nothing
                        //}
                     //})
                    .setIcon(android.R.drawable.ic_dialog_alert)
                     .show();
                    hidePDialog();

                }
            });
    AppController.getInstance().addToRequestQueue(movieReq);    
    listView.setAdapter(adapter);

}

private View getActionBar() {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}

private void hidePDialog() {
if (pDialog != null) {
    pDialog.dismiss();
    pDialog = null;
}
}

}

1 个答案:

答案 0 :(得分:0)

你可以尝试这个(我在onStart()的最后一行添加了一行来设置新的列表位置)

使用此行,您可以设置新位置_

listView.setSelectionFromTop(newPosition, 0); 使用第一个参数设置位置,然后使用第二个参数从列表顶部设置distnace

@Override
public void onStart(){
super.onStart();
// calling adapter changes here, just
// to avoid getactivity()null
// increment current page
current_page += 1;

// Next page request
URL = "http:url&page=" + current_page;
//adapter = new CustomListAdapter(this, movieList);

// changing action bar color
//getActivity().getActionBar().setBackground(
        //new ColorDrawable(Color.parseColor("#1b1b1b")));

// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(URL,
        new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                Log.d(TAG, response.toString());
                hidePDialog();

                // Parsing json
                for (int i = 0; i < response.length(); i++) {
                    try {

                        JSONObject obj = response.getJSONObject(i);
                        Movie movie = new Movie();
                        movie.setDate(obj.getString("date"));
                        movie.setId(obj.getString("id"));

                        movieList.add(movie);
                        int currentPosition = listView.getFirstVisiblePosition();

                        adapter = new CustomListAdapter(getActivity(), movieList);
                        adapter.notifyDataSetChanged();

                        listView.setAdapter(adapter);
                        listView.setSelectionFromTop(currentPosition + 1, 0);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }                       
            }
        },new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                new AlertDialog.Builder(getActivity())
                .setTitle("No Connectivity ")
                .setMessage("Please check your internet connectivity!")
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) { 
                        // continue with delete
                    }
                 })
                //.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                    //public void onClick(DialogInterface dialog, int which) { 
                        // do nothing
                    //}
                 //})
                .setIcon(android.R.drawable.ic_dialog_alert)
                 .show();
                hidePDialog();

            }
        });
AppController.getInstance().addToRequestQueue(movieReq);    
listView.setAdapter(adapter);
//Set the new position
listView.setSelectionFromTop(currentPosition  + 1, 0);
 }