尝试为ListView创建一个EndlessScrollListener?

时间:2015-09-16 00:51:31

标签: android android-listview

我正在尝试创建一个ListView来对Web服务RestFull的结果进行分页。问题是onLoadMoreonCreateView设置setOnScrollListener时始终在onLoadMore执行,这总是从webservice返回所有数据。我怀疑的是,只有当我需要在ListView上触及更多数据而不是在onCreateView中打开时,我才能执行此public abstract class EndlessScrollListener implements AbsListView.OnScrollListener { // The minimum amount of items to have below your current scroll position // before loading more. private int visibleThreshold = 2; // The current offset index of data you have loaded private int currentPage = 0; // The total number of items in the dataset after the last load private int previousTotalItemCount = 0; // True if we are still waiting for the last set of data to load. private boolean loading = true; // Sets the starting page index private int startingPageIndex = 0; public EndlessScrollListener() { } public EndlessScrollListener(int visibleThreshold) { this.visibleThreshold = visibleThreshold; } public EndlessScrollListener(int visibleThreshold, int startPage) { this.visibleThreshold = visibleThreshold; this.startingPageIndex = startPage; this.currentPage = startPage; } // This happens many times a second during a scroll, so be wary of the code you place here. // We are given a few useful parameters to help us work out if we need to load some more data, // but first we check if we are waiting for the previous load to finish. @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // If the total item count is zero and the previous isn't, assume the // list is invalidated and should be reset back to initial state if (totalItemCount < previousTotalItemCount) { this.currentPage = this.startingPageIndex; this.previousTotalItemCount = totalItemCount; if (totalItemCount == 0) { this.loading = true; } } // If it’s still loading, we check to see if the dataset count has // changed, if so we conclude it has finished loading and update the current page // number and total item count. if (loading && (totalItemCount > previousTotalItemCount)) { loading = false; previousTotalItemCount = totalItemCount; currentPage++; } // If it isn’t currently loading, we check to see if we have breached // the visibleThreshold and need to reload more data. // If we do need to reload some more data, we execute onLoadMore to fetch the data. if (!loading && (totalItemCount - visibleItemCount)<=(firstVisibleItem + visibleThreshold)) { onLoadMore(currentPage + 1, totalItemCount); loading = true; } } // Defines the process for actually loading more data based on page public abstract void onLoadMore(int page, int totalItemsCount); @Override public void onScrollStateChanged(AbsListView view, int scrollState) { // Don't take any action on changed } }

我正在尝试这个。

EndlessScrollListener

public class NoticiaFrag extends Fragment {
    private ListView lvNoticias;
    private List<Noticia> listaNoticias = new ArrayList<Noticia>();
    private NoticiaListAdapter noticiaLA;
    private static final String TAG = "NoticiaFrag";
    protected ProgressDialog progressDialog;

    //offset start in 0
    private static Integer OFFSET = 0;

    //singleton
    private static NoticiaFrag mFrag;

    public static NoticiaFrag newInstance() {
        if(mFrag == null){
            mFrag = new NoticiaFrag();
        }
        return mFrag;
    }

    public NoticiaFrag() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view =  inflater.inflate(R.layout.noticia_frag, container, false);

        lvNoticias = (ListView)view.findViewById(R.id.lvNoticias);
        lvNoticias.setOnScrollListener(new EndlessScrollListener() {
            @Override
            public void onLoadMore(int page, int totalItemsCount) {
                OFFSET += 2;
                moreData();
            }
        });

        return view;
    }



    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getAllNoticias();
    }


    /** retorna todas as noticias */
    private void getAllNoticias(){
        progressDialog = new CustomProgressDialog().getCustomProgress(null, getView().getContext());
        progressDialog.show();
        try {
            JsonObjectRequest app = new NoticiaDAO().getAllNoticias(OFFSET, new NoticiasAdapter() {
                @Override
                public void getAllNoticias(List<Noticia> lista) {
                    Log.w("SIZELIST->", lista.size() + "") ;
                    if(!lista.isEmpty()){
                        listaNoticias = lista;
                        noticiaLA = new NoticiaListAdapter(getView().getContext(), listaNoticias);
                        lvNoticias.setAdapter(noticiaLA);
                    }else{
                        Toast.makeText(getView().getContext(), "Nenhuma noticia encontrada", Toast.LENGTH_SHORT).show();
                    }
                    progressDialog.dismiss();
                }
            });
            CustomVolleySingleton.getInstance().addToRequestQueue(app);
        }catch (Exception e ){
            Log.e("ERROR: " + TAG, "Method: " + "getAllNoticias: " + e);
        }
    }

    // Append more data into the adapter
    public void moreData() {
        progressDialog = new CustomProgressDialog().getCustomProgress(null, getView().getContext());
        progressDialog.show();
        try {
            JsonObjectRequest app = new NoticiaDAO().getAllNoticias(OFFSET, new NoticiasAdapter() {
                @Override
                public void getAllNoticias(List<Noticia> lista) {
                    if(listaNoticias.size() > 0){
                        noticiaLA.changeLista(lista);
                        Log.w("MORE_DATA->", noticiaLA.getCount() + "");
                    }else{
                        Toast.makeText(getView().getContext(), "Nenhuma noticia encontrada", Toast.LENGTH_SHORT).show();
                    }
                    progressDialog.dismiss();
                }
            });
            CustomVolleySingleton.getInstance().addToRequestQueue(app);
        }catch (Exception e ){
            Log.e("ERROR: " + TAG, "Method: " + "getAllNoticias: " + e);
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        ChangeActionBar.changeActionBar(getActivity(), "Notícias", false, "");
    }


    @Override
    public void onPause() {
        super.onPause();
        CustomVolleySingleton.getInstance().cancelPendingRequests(CustomVolleySingleton.TAG);
        ChangeActionBar.changeActionBar(getActivity(), null, false, "");
        OFFSET = 0;
    }

}

片段

=IF(A2=D2,B2,"")

1 个答案:

答案 0 :(得分:0)

问题解决了。

<强>片段

public class NoticiaFrag extends Fragment {
    private ListView lvNoticias;
    private ProgressBar pbProgress;
    private List<Noticia> listaNoticias = new ArrayList<Noticia>();
    private NoticiaListAdapter noticiaLA;
    private static final String TAG = "NoticiaFrag";
    protected ProgressDialog progressDialog;

    //offset start in 0
    private static Integer OFFSET = 0;

    //singleton
    private static NoticiaFrag mFrag;

    public static NoticiaFrag newInstance() {
        if(mFrag == null){
            mFrag = new NoticiaFrag();
        }
        return mFrag;
    }

    public NoticiaFrag() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view =  inflater.inflate(R.layout.noticia_frag, container, false);

        lvNoticias = (ListView)view.findViewById(R.id.lvNoticias);
        pbProgress = (ProgressBar)view.findViewById(R.id.pbProgress);

        lvNoticias.setOnScrollListener(new EndlessScrollListener() {
            @Override
            public void onLoadMore(int page, int totalItemsCount) {
                moreData();
            }
        });

        return view;
    }



    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getAllNoticias();
    }


    /** retorna todas as noticias */
    private void getAllNoticias(){
        pbProgress.setVisibility(View.VISIBLE);
        try {
            JsonObjectRequest app = new NoticiaDAO().getAllNoticias(OFFSET, new NoticiasAdapter() {
                @Override
                public void getAllNoticias(List<Noticia> lista) {
                    Log.w("SIZELIST->", lista.size() + "") ;
                    if(!lista.isEmpty()){
                        listaNoticias = lista;
                        noticiaLA = new NoticiaListAdapter(getView().getContext(), listaNoticias);
                        lvNoticias.setAdapter(noticiaLA);
                    }else{
                        Toast.makeText(getView().getContext(), "Nenhuma noticia encontrada", Toast.LENGTH_SHORT).show();
                    }
                    pbProgress.setVisibility(View.GONE);
                }
            });
            CustomVolleySingleton.getInstance().addToRequestQueue(app);
        }catch (Exception e ){
            Log.e("ERROR: " + TAG, "Method: " + "getAllNoticias: " + e);
        }
    }

    // Append more data into the adapter
    public void moreData() {
        OFFSET += 5;
        Log.i("OFFSET", OFFSET + "");
        pbProgress.setVisibility(View.VISIBLE);
        try {
            JsonObjectRequest app = new NoticiaDAO().getAllNoticias(OFFSET, new NoticiasAdapter() {
                @Override
                public void getAllNoticias(List<Noticia> lista) {
                    if(listaNoticias.size() > 0){
                        if(noticiaLA == null){
                            listaNoticias = lista;
                            noticiaLA = new NoticiaListAdapter(getView().getContext(), listaNoticias);
                            lvNoticias.setAdapter(noticiaLA);
                        }else{
                            noticiaLA.changeLista(lista);
                        }
                        Log.w("MORE_DATA->", noticiaLA.getCount() + "");
                    }else{
                        Toast.makeText(getView().getContext(), "Nenhuma noticia encontrada", Toast.LENGTH_SHORT).show();
                    }
                    pbProgress.setVisibility(View.GONE);
                }
            });
            CustomVolleySingleton.getInstance().addToRequestQueue(app);
        }catch (Exception e ){
            Log.e("ERROR: " + TAG, "Method: " + "getAllNoticias: " + e);
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        ChangeActionBar.changeActionBar(getActivity(), "Notícias", false, "");
    }


    @Override
    public void onPause() {
        super.onPause();
        CustomVolleySingleton.getInstance().cancelPendingRequests(CustomVolleySingleton.TAG);
        ChangeActionBar.changeActionBar(getActivity(), null, false, "");
        OFFSET = 0;
    }

}

<强>适配器

public class NoticiaListAdapter extends BaseAdapter {
    private Context context;
    private List<Noticia> lista;


    public NoticiaListAdapter(Context context, List<Noticia> lista) {
        this.context = context;
        this.lista = lista;
    }


    public void changeLista(List<Noticia> lista){
        this.lista.addAll(lista);
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return lista.size();
    }

    @Override
    public Object getItem(int position) {
        return lista.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        Noticia noticia = lista.get(position);
        if (convertView == null) {
            holder = new ViewHolder();
            LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.noticia_listadapter, parent, false);

            holder.llNoticiaListAdapter = (LinearLayout) convertView.findViewById(R.id.llNoticiaListAdapter);
            holder.sivNoticia = (SmartImageView)convertView.findViewById(R.id.sivNoticia);
            holder.tvTitulo = (TextView) convertView.findViewById(R.id.tvTitulo);
            holder.wvDescricao = (WebView) convertView.findViewById(R.id.wvDescricao);
            holder.tvData = (TextView) convertView.findViewById(R.id.tvData);
            holder.tvAutor = (TextView) convertView.findViewById(R.id.tvAutor);

            convertView.setTag(holder);
        }else{
            holder = (ViewHolder)convertView.getTag();
        }


        if(noticia.getImage() == null){
            holder.sivNoticia.setImageDrawable(context.getResources().getDrawable(R.drawable.no_image_news));
        }else{
            holder.sivNoticia.setImageUrl(WebServiceURL.getBaseWebServiceURL() + "app/webroot/img/noticias/" + noticia.getImage());
        }

        holder.tvTitulo.setText(noticia.getTitulo());
        holder.wvDescricao.loadData(formatDescricao(noticia.getDescricao()), "text/html; charset=utf-8", null);
        holder.tvData.setText(new DateControl().getDataHoraFormat(noticia.getCreated()));
        holder.tvAutor.setText("Por: " + noticia.getUsuario());

        return convertView;
    }

    private String formatDescricao(String descricao){
        StringBuilder html = new StringBuilder();
        html.append("<html>");
        html.append("<body>");
        html.append("<small>");
        html.append("<p align=\"justify\" style=\"color:gray\">");
        html.append(descricao);
        html.append("</p");
        html.append("</small>");
        html.append("</body>");
        html.append("</html>");

        return html.toString();

    }

    private static class ViewHolder{
        LinearLayout llNoticiaListAdapter;
        SmartImageView sivNoticia;
        TextView tvTitulo;
        WebView wvDescricao;
        TextView tvData;
        TextView tvAutor;

    }
}

WebService CakePHP

public function getAllNoticias(){ 
            $json = $this->request->input("json_decode", true);
            //$limit = $json["limit"];
            $offset = $json["offset"];            

            $noticias = $this->Noticia->find("all", array("fields"=> array(
                                                                        "Noticia.id",
                                                                        "Noticia.titulo",
                                                                        "Noticia.descricao",
                                                                        "Noticia.usuario",
                                                                        "Noticia.image",
                                                                        "Noticia.created"                
                                                                        ),
                                                            "order"=>"Noticia.created desc",
                                                            "offset"=>$offset,
                                                            "limit"=>5,
                                                     ));
            $this->set("noticias", $noticias);
            $this->set("_serialize", array("result"=>"noticias"));             
        }