【问题标题】:ListView - Load more items with scrollListView - 使用滚动加载更多项目
【发布时间】:2014-01-14 13:44:35
【问题描述】:

我在片段中使用的列表视图需要帮助。该应用程序从 API 读取数据,我的代码工作正常。我最初加载了 15 个项目,并且每次我再加载 10 个项目。但是,如果对 API 的请求返回的项目少于 15 个,则它不起作用。此外,当项目数不是 15 或 25 或 35 的倍数时,应用程序会失败。那是因为我在初始设置后加载了 10 个项目。

我需要修改我的代码以使其适用于任意数量的列表项。

我的代码如下:

(ListaFragment.java) -> 这是 ListFragment

    public class ListaFragment extends ListFragment implements OnScrollListener {
    public ListaFragment(){}
    View rootView;

    ListAdapter customAdapter = null;
    ListaLugares listaLugares;    

    // values to pagination
    private View mFooterView;
    private final int AUTOLOAD_THRESHOLD = 4;
    private int MAXIMUM_ITEMS;
    private Handler mHandler;
    private boolean mIsLoading = false;
    private boolean mMoreDataAvailable = true;
    private boolean mWasLoading = false;

    public int ventana = 0;
    public int nInitial;

    private Runnable mAddItemsRunnable = new Runnable() {
        @Override
        public void run() {
            customAdapter.addMoreItems(10);
            mIsLoading = false;

        }
    };


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        rootView = inflater.inflate(R.layout.fragment_lista, container, false);

        if (container != null) {
            container.removeAllViews();
        }

        ((MainActivity) getActivity()).setBar();


        // read number of places of a category
        listaLugares.readNumberOfPlaces();
        // set
        setNumbersOfItems();
        // read the places a insert in a List
        listaLugares.readPlaces(15, ventana, listaLugares.idCategoria);
        //ventana = ventana + 25;

        return rootView;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        listaLugares = ((ListaLugares)getActivity().getApplicationContext());
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        final Context context = getActivity();
        mHandler = new Handler();
        customAdapter = new ListAdapter(context, listaLugares.lista);

        mFooterView = LayoutInflater.from(context).inflate(R.layout.loading_view, null);
        getListView().addFooterView(mFooterView, null, false);
        setListAdapter(customAdapter);
        getListView().setOnScrollListener(this);
    }


    public void setNumbersOfItems() {
        if (listaLugares.totalItems > 100) {
            MAXIMUM_ITEMS = 100;
            nInitial = 25;
        } else {
            MAXIMUM_ITEMS = listaLugares.totalItems;
            nInitial = listaLugares.totalItems;
        }
        Log.v("NUMBER OF ITEMS", "Number: " + MAXIMUM_ITEMS + "-"+ nInitial);
    }



    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);

        //Intent myIntent = new Intent(getActivity(), DetalleActivity.class);
        //myIntent.putExtra("param_id", appState.lista.get(position).id);
        //getActivity().startActivity(myIntent); 
    }


    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
                         int visibleItemCount, int totalItemCount) {

         if (!mIsLoading && mMoreDataAvailable) {
             if (totalItemCount >= MAXIMUM_ITEMS) {
                 mMoreDataAvailable = false;
                 getListView().removeFooterView(mFooterView);
             } else if (totalItemCount - AUTOLOAD_THRESHOLD <= firstVisibleItem + visibleItemCount) {
                 ventana = ventana + 10;
                 listaLugares.readPlaces(10, ventana, listaLugares.idCategoria);
                 mIsLoading = true;
                     mHandler.postDelayed(mAddItemsRunnable, 1000);
             }
         }
    }


    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        // Ignore
    }


    @Override
    public void onStart() {
        super.onStart();
        if (mWasLoading) {
            mWasLoading = false;
            mIsLoading = true;
            mHandler.postDelayed(mAddItemsRunnable, 1000);
        }
    }


    @Override
    public void onStop() {
        super.onStop();
        mHandler.removeCallbacks(mAddItemsRunnable);
        mWasLoading = mIsLoading;
        mIsLoading = false;
        ventana = ventana;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

(ListAdapter.java) -> 适配器类中添加更多项目的方法。

    public class ListAdapter extends ArrayAdapter<Lugar> {
Context context;
List<Lugar> values;

ListaLugares listaLugares;

private int mCount = 20;


public ListAdapter(Context context, List<Lugar> values) {
    super(context, R.layout.row, values);
    this.context = context;
    this.values = values;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;

    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    row = inflater.inflate(R.layout.row, parent, false);
    TextView firstText = (TextView) row.findViewById(R.id.titulo);
    TextView secondText = (TextView) row.findViewById(R.id.categoria);

    firstText.setText(values.get(position).nombre);
    secondText.setText(values.get(position).categoriaNombre);

    return row;
}


public void addMoreItems(int count) {
    mCount += count;
    notifyDataSetChanged();
}

@Override
public int getCount() {
    return mCount;
}


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

}

【问题讨论】:

  • 请仅在问题中包含related code,请参阅sscce.org
  • 好的,我已经在 ListAdapter 中编辑了代码,但我无法总结 ListaFragment,因为所有代码都很重要。感谢您的建议;)
  • 你可以查看 ApiDemos,有一个很好的例子。

标签: java android android-listview android-listfragment android-scrollview


【解决方案1】:

我加入了以前编辑的版本以查看一些代码。

第一次调用有效,因为您从 initiaItems 上的值 15 开始,并在 ListAdapter 构造函数上将其设置为 mCount

public ListAdapter(Context context, List<Lugar> values, int count) {
    super(context, R.layout.row, values);
    this.context = context;
    this.values = values;
    this.mCount = count;
}

所以当android渲染listview时,它访问函数ListAdapter.getCount()并返回mCount(15)。

但是当你滚动它可以调用到

public void addMoreItems(int count, int idCategoria) {
    appState = ((ListaLugares)getContext().getApplicationContext());
    appState.readPlaces(15, mCount, idCategoria);
    mCount += count;
    notifyDataSetChanged();
}

如果 appState.readPlaces 返回的项目数未知,为什么要向 mCount mCount += count; 添加一个数字?

如果 appState.readPlaces 返回 14 并且 count 在呈现列表视图时为 15,则当有 15+14 时,它将假设有 15+15 个项目,因此最后一个项目将崩溃。

mCount 应该从保留 API 调用数据的对象中获取长度,在您的情况下,我认为它将是 appState.lista

【讨论】:

  • 我修改了我的代码,但我无法解决我的问题。我的新代码有问题。我跟着下一个教程:informit.com/articles/article.aspx?p=2066699&seqNum=4
  • 如果我们有值列表怎么样return (mCount &gt; values.size()) ? values.size() : mCount而不是return mCount
猜你喜欢
  • 2013-08-15
  • 2014-03-03
  • 2016-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-10
  • 2017-05-06
  • 1970-01-01
相关资源
最近更新 更多