如何实现在列表视图中适当的滚动来实现对片段活动分页? [英] How to implement a proper scroll in list view to implement pagination on fragment activity?

查看:94
本文介绍了如何实现在列表视图中适当的滚动来实现对片段活动分页?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建立像TechCrunch的应用程序。我取出由JSON格式的服务器数据,并在像文章标题,作者姓名和图像列表视图中显示的数据。我已经申请分页意味着,当用户滚动更多的文章列表视图加载。我的分页工作正常,但作为新鲜或新的数据加载滚动剂量不与数据对齐有一个在滚动功能的问题。为了澄清更简单的话我的滚动-ER在去的时候我其实向下滚动页面的顶部,这是我的code:

 公共类OneFragment扩展片段{公共OneFragment(){}
私有静态最后弦乐TAG = OneFragment.class.getSimpleName();//电影JSON网址
私有静态字符串URL =HTTP:URL和放大器;页= 1;
私人ProgressDialog pDialog;
私人列表<电影及GT; movieList =新的ArrayList<电影及GT;();
私人的ListView ListView的;
私人CustomListAdapter适配器;
INT CURRENT_PAGE = 1;
INT米preLAST;
@覆盖
 公共查看onCreateView(LayoutInflater充气器,容器的ViewGroup,
        捆绑savedInstanceState){    最后查看rootView = inflater.inflate(R.layout.swip,集装箱,FALSE);    pDialog =新ProgressDialog(getActivity());
    pDialog.setMessage(正在加载...);
    pDialog.show();
    pDialog.setCancelable(假);
    ListView控件=(ListView控件)rootView.findViewById(R.id.list49);
    listView.setOnScrollListener(新AbsListView.OnScrollListener()
    {
        @覆盖
        公共无效onScrollStateChanged(AbsListView absListView,int i)以
        {        }        @覆盖
        公共无效onScroll(AbsListView观点,诠释firstVisibleItem,诠释visibleItemCount,诠释totalItemCount)
        {
            INT lastItem = firstVisibleItem + visibleItemCount;
               如果(lastItem == totalItemCount){
                   如果(M preLAST!= lastItem)
                   {
                       米preLAST = lastItem;
                       调用onStart();                   }
            }
        }
    });    listView.setOnItemClickListener(新OnItemClickListener(){        @覆盖
        公共无效onItemClick(适配器视图<>适配器视图,视图观点,INT位置,
                长偏移){
            // TODO自动生成方法存根
            电影项=(动画)adapter.getItem(位置);
            意向意图=新意图(rootView.getContext(),SingleArticle.class);
            single.date = item.getDate();
            single.id = item.getId();
            startActivity(意向);
            }
        });
    // pDialog =新ProgressDialog(本);
    //发出HTTP请求之前显示进度对话框    返回rootView;
}@覆盖
公共无效调用onStart(){
    super.onStart();
    //调用适配器的变化在这里,只需
    //避免getactivity()空
    //增加当前页面
    CURRENT_PAGE + = 1;    //下一个页面请求
    URL =HTTP:URL和放大器;页=+ CURRENT_PAGE;
    //适配器=新CustomListAdapter(这一点,movieList);    //改变操作栏的颜色
    // getActivity()。getActionBar()的setBackground(
            //新ColorDrawable(Color.parseColor(#1b1b1b)));    //创建凌空要求OBJ
    JsonArrayRequest movieReq =新JsonArrayRequest(URL,
            新Response.Listener< JSONArray>(){
                @覆盖
                公共无效onResponse(JSONArray响应){
                    Log.d(TAG,response.toString());
                    hidePDialog();                    //解析JSON
                    的for(int i = 0; I< response.length();我++){
                        尝试{                            JSONObject的OBJ = response.getJSONObject(I)
                            电影电影=新电影();
                            movie.setDate(obj.getString(DATE));
                            movie.setId(obj.getString(ID));                            movieList.add(电影);
                            INT currentPosition = listView.getFirstVisiblePosition();                            适配器=新CustomListAdapter(getActivity(),movieList);
                            adapter.notifyDataSetChanged();                            listView.setAdapter(适配器);
                            listView.setSelectionFromTop(currentPosition + 1,0);
                        }赶上(JSONException E){
                            e.printStackTrace();
                        }
                    }
                }
            },新Response.ErrorListener(){
                @覆盖
                公共无效onErrorResponse(VolleyError错误){
                    VolleyLog.d(TAG,错误:+ error.getMessage());
                    新AlertDialog.Builder(getActivity())
                    .setTitle(无连接)
                    .setMessage(请检查您的网络连接!)
                    .setPositiveButton(android.R.string.yes,新DialogInterface.OnClickListener(){
                        公共无效的onClick(DialogInterface对话,诠释它){
                            //继续删除
                        }
                     })
                    //.setNegativeButton(android.R.string.no,新DialogInterface.OnClickListener(){
                        //公共无效的onClick(DialogInterface对话,诠释它){
                            // 没做什么
                        //}
                     //})
                    .setIcon(android.R.drawable.ic_dialog_alert)
                     。显示();
                    hidePDialog();                }
            });
    。AppController.getInstance()addToRequestQueue(movieReq);
    listView.setAdapter(适配器);}私人查看getActionBar(){
    // TODO自动生成方法存根
    返回null;
}@覆盖
公共无效的onDestroy(){
super.onDestroy();
hidePDialog();
}私人无效hidePDialog(){
如果(pDialog!= NULL){
    pDialog.dismiss();
    pDialog = NULL;
}
}}


解决方案

您可以试试这个(我加一条线,设置在onStart的最后一行新的列表中的位置())

通过这条线,你可以设置新的位置_

listView.setSelectionFromTop(在newPosition,0);
与第一参数设置的位置,并与第二设置从列表的顶部distnace

  @覆盖
公共无效调用onStart(){
super.onStart();
//调用适配器的变化在这里,只需
//避免getactivity()空
//增加当前页面
CURRENT_PAGE + = 1;//下一个页面请求
URL =HTTP:URL和放大器;页=+ CURRENT_PAGE;
//适配器=新CustomListAdapter(这一点,movieList);//改变操作栏的颜色
// getActivity()。getActionBar()的setBackground(
        //新ColorDrawable(Color.parseColor(#1b1b1b)));//创建凌空要求OBJ
JsonArrayRequest movieReq =新JsonArrayRequest(URL,
        新Response.Listener< JSONArray>(){
            @覆盖
            公共无效onResponse(JSONArray响应){
                Log.d(TAG,response.toString());
                hidePDialog();                //解析JSON
                的for(int i = 0; I< response.length();我++){
                    尝试{                        JSONObject的OBJ = response.getJSONObject(I)
                        电影电影=新电影();
                        movie.setDate(obj.getString(DATE));
                        movie.setId(obj.getString(ID));                        movieList.add(电影);
                        INT currentPosition = listView.getFirstVisiblePosition();                        适配器=新CustomListAdapter(getActivity(),movieList);
                        adapter.notifyDataSetChanged();                        listView.setAdapter(适配器);
                        listView.setSelectionFromTop(currentPosition + 1,0);
                    }赶上(JSONException E){
                        e.printStackTrace();
                    }
                }
            }
        },新Response.ErrorListener(){
            @覆盖
            公共无效onErrorResponse(VolleyError错误){
                VolleyLog.d(TAG,错误:+ error.getMessage());
                新AlertDialog.Builder(getActivity())
                .setTitle(无连接)
                .setMessage(请检查您的网络连接!)
                .setPositiveButton(android.R.string.yes,新DialogInterface.OnClickListener(){
                    公共无效的onClick(DialogInterface对话,诠释它){
                        //继续删除
                    }
                 })
                //.setNegativeButton(android.R.string.no,新DialogInterface.OnClickListener(){
                    //公共无效的onClick(DialogInterface对话,诠释它){
                        // 没做什么
                    //}
                 //})
                .setIcon(android.R.drawable.ic_dialog_alert)
                 。显示();
                hidePDialog();            }
        });
。AppController.getInstance()addToRequestQueue(movieReq);
listView.setAdapter(适配器);
//设置新的位置
listView.setSelectionFromTop(currentPosition + 1,0);
 }

I am building an application like techcrunch. I am fetching data from server in JSON format and displaying the data in list view like article title,author name and image. I have applied pagination means when user scroll more articles load in a list view. My pagination works fine but there is an issue in the scroll function as the fresh or new data loads the scroll dose not aligns with the data. To clarify more in simple words my scroll-er goes at the top of the page when i am actually scrolling down this is my code :

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;
}
}

}

解决方案

You can try this (I added a line to set the new list position in the last line of onStart())

With this line you can set the new position_

listView.setSelectionFromTop(newPosition, 0); With the first parameter you set the position, and with the second you set the distnace from the top of the list

@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);
 }

这篇关于如何实现在列表视图中适当的滚动来实现对片段活动分页?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆