简体   繁体   English

如何在我的 listview android studio 中进行某种延迟加载

[英]How to do some kind of lazy load in my listview android studio

I created one fragment and I'm populating a list view in it using Retrofit for network connection and get request and I created custom adapter to populate list view:我创建了一个片段,并在其中使用 Retrofit 填充列表视图以进行网络连接并获取请求,并创建了自定义适配器来填充列表视图:

public class TransactionsAdapter extends BaseAdapter {
ArrayList<Transactions> transactions;


public TransactionsAdapter(ArrayList<Transactions> transactions) {
    this.transactions=transactions;
}

@Override
public int getCount() {
    if (transactions.size()<20) {
        return transactions.size();
    }else return 20;

}

@Override
public Object getItem(int position) {
    return transactions.get(position);
}
@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view=null;
    ViewHolder viewHolder = null;

    if(convertView == null)
    {
        view = LayoutInflater.from(parent.getContext()).inflate(R.layout.izvjestaji_item,parent,false);
        viewHolder = new ViewHolder(view);
        view.setTag(viewHolder);

    }
    else{
        view = convertView;
        viewHolder= (ViewHolder) view.getTag();

    }

    Transactions transactions = (Transactions) getItem(position);

    if(transactions != null) {

        viewHolder.datum.setText(transactions.getShortDate());
        viewHolder.partner.setText(transactions.getMerchantName());
        String doublestring=Double.toString(transactions.getTransactionPointsAmount());
        String doublestring1=Double.toString(transactions.getSalesAmount());
        viewHolder.iznos.setText(doublestring1);
        viewHolder.brojbodova.setText(doublestring);
    }

    return view;
}


private class ViewHolder{
    TextView datum;
    TextView partner;
    TextView iznos;
    TextView brojbodova;

    public ViewHolder(View view) {
        this.datum = (TextView) view.findViewById(R.id.izvjestaji_datum);
        this.partner = (TextView) view.findViewById(R.id.izvjestaji_partner);
        this.iznos = (TextView) view.findViewById(R.id.izvjestaji_iznos);
        this.brojbodova=(TextView)view.findViewById(R.id.izvjestaji_brojbodova);
    }
}
}

I have created 2 layouts for item and for list view and It's all working like it should.我为项目和列表视图创建了 2 个布局,并且一切正常。 Now I need to add some kind of lazy load or something simpler because there is a chance that server will return a lot of data and I want to show them like 20 by 20 to increase network efficient .现在我需要添加某种延迟加载或更简单的东西,因为服务器有可能会返回大量数据,我想将它们显示为 20 x 20 以提高网络效率。 This is my fragment code:这是我的片段代码:

    public class Izvjestaji extends Fragment {
   // The onCreateView method is called when Fragment should create its View   
   object hierarchy,
 // either dynamically or via XML layout inflation.
 ListView list;
 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle   
 savedInstanceState) {
    // Defines the xml file for the fragment


    return inflater.inflate(R.layout.izvjestaji, parent, false);

 }

// This event is triggered soon after onCreateView().
// Any view setup should occur here.  E.g., view lookups and attaching view          
listeners.
@Override
 public void onViewCreated(View view, Bundle savedInstanceState)  {
    list=(ListView)view.findViewById(R.id.izvjestaji_list);
    showList();
    // Setup any handles to view objects here
    // EditText etFoo = (EditText) view.findViewById(R.id.etFoo);

 }
 public void showList(){

    NetworkSDK.getInstance().getTransactions(new     
    Callback<List<Transactions>>() {
        @Override
        public void onResponse(Call<List<Transactions>> call,        
        Response<List<Transactions>> response) {
            if(response.isSuccess()){
                Log.d("Data", String.valueOf(response.isSuccess()));
                TransactionsAdapter transactionsAdapter=new 
        TransactionsAdapter((ArrayList<Transactions>)response.body());
                list.setAdapter(transactionsAdapter);


            }
        }

        @Override
        public void onFailure(Call<List<Transactions>> call, Throwable t) {
            Log.d("Error","Def error");

        }
    });
 }
 }

This is my call from Network SDK in retrofit这是我在改造中来自 Network SDK 的调用

    public void getTransactions(Callback<List<Transactions>>callback){
    Call<List<Transactions>>call =                                                                                                           
    BaseClient.getService().getTransactions(4,2016);
            call.enqueue(callback);
}

From all of this I get a listview in my fragment that show all available transactions that I want to show but I need to limit it to about 20 and when user Swipe bottom it need to show another 20 and so on.通过所有这些,我在片段中获得了一个列表视图,它显示了我想要显示的所有可用交易,但我需要将其限制为大约 20 个,当用户滑动底部时,它需要显示另外 20 个,依此类推。 I got some idea like to send some index number when user swipe or similar but I'm sure that there is some easier way because I'm not that good with android.我有一些想法,比如在用户滑动或类似操作时发送一些索引号,但我确信有一些更简单的方法,因为我对 android 不太好。

I also tried things like endless adapter but I am not allowed to use libraries that are not really popular like retrofit or volley and this one: https://github.com/commonsguy/cwac-endless is not providing suppor anymore and I'm not even sure is it still valid我也尝试过诸如无限适配器之类的东西,但我不允许使用不太流行的库,例如改造或凌空抽射,而这个: https : //github.com/commonsguy/cwac-endless不再提供支持,我甚至不确定它是否仍然有效

use OnScrollListener to detect whether list scrolled to down or not .使用OnScrollListener检测列表是否向下滚动。 and then load data .然后加载数据。

  mListView.setOnScrollListener(new OnScrollListener() {

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

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        if (mListView.getAdapter() == null)
            return ;

        if (mListView.getAdapter().getCount() == 0)
            return ;

        int l = visibleItemCount + firstVisibleItem;
        if (l >= totalItemCount && !isLoading) {
            // It is time to add new data. We call the listener
            isLoading = true;
            loadYourData();
        }
    }
});

after loading data don't forgot to refresh your list in adapter.加载数据后不要忘记刷新适配器中的列表。

public void updateInUi() {

    // send your request and get list of updated items
    List<> newItems = getYourUpdatedListHere()
    yourDataList.addAll(newItems);
    adapter.notifyDataSetChanged();
}

Another method to detect if the list's end has been reached is inside getView method of your Adapter as such:检测是否已到达列表末尾的另一种方法是在您的Adapter getView方法中,如下所示:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (position == getCount() - 1) { // scrolled to last item
        if (mRepo.hasMore()) { // if there are more items than we are displaying
            new MyAsyncLoaderTask().execute();
        }
    }
    // usual getView implementation follows...
    return view;
}

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

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