如何使用底部的两个视图和进度条进行recyclerview?

时间:2017-07-25 07:26:31

标签: android android-recyclerview progress-bar android-progressbar

我有一个应用程序,其条件是这样的,我必须显示服务器数据与谷歌添加随机数,当用户向上滚动时进度条我想在Recyclerview底部显示进度条,将发送服务器请求要设置更多数据viewType我声明了int类型变量,即viewType和设置活动中的视图类型。但它不起作用。请帮忙

模特代码: -

  private String email;
private String phone;

public int getViewType() {
    return viewType;
}

public void setViewType(int viewType) {
    this.viewType = viewType;
}

private int viewType;

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getPhone() {
    return phone;
}

public void setPhone(String phone) {
    this.phone = phone;
}

活动代码: -

private List<Contact> contacts;
Contact contact;
private ContactAdapter contactAdapter;
private Random random;
private RecyclerView recyclerView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    contacts = new ArrayList<>();
    random = new Random();
    sendRequesttoServerForDeals();

    //find view by id and attaching adapter for the RecyclerView
    recyclerView = (RecyclerView) findViewById(R.id.recycler_view);

    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    contactAdapter = new ContactAdapter(recyclerView, contacts, getApplicationContext());


    //set load more listener for the RecyclerView adapter
    contactAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
        @Override
        public void onLoadMore() {
                contacts.add(null);
                contactAdapter.notifyItemInserted(contacts.size() - 1);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        contacts.remove(contacts.size() - 1);
                        contactAdapter.notifyItemRemoved(contacts.size());
                        sendRequesttoServerForMoreDeals();

                    }
                }, 3000);

        }
    });
}
/**
 * Method is called to send server request for manual deals.
 */
public void sendRequesttoServerForDeals() {

    JSONObject jsonObject = new JSONObject();
    String dealListUrl = "http://156.222.16.1156:8985/ireward/rest/json/metallica";
    JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, dealListUrl.trim(), jsonObject, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
                Log.e("MainActivity", "Server success response::" + response);
            String resultCode = "resultcode";
            try {
                int nResultCodeFromServer = Integer.parseInt(response.getString(resultCode.trim()));
                if (nResultCodeFromServer == ConstantInt.TRANSACTION_SUCCESS) {
                    JSONArray getJsonArray = response.optJSONArray(CResponseKey.DEAL_ARRAY.trim());
                    contacts.clear();

                    for (int i = 0; i < getJsonArray.length(); i++) {
                        try {
                            JSONObject getJsonObj = getJsonArray.getJSONObject(i);
                            contact = new Contact();
                            contact.setEmail(getJsonObj.getString(CResponseKey.DEAL_NAME.trim()));
                            contact.setPhone(getJsonObj.getString(CResponseKey.DEAL_DETAIL.trim()));
                            contact.setViewType(0);
                            contacts.add(contact);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }

                    int arrayCount = getJsonArray.length();
                    Log.e("Mainactivity", "ArrayCount::" + arrayCount);
                    Contact contact = new Contact();
                    contact.setViewType(1);
                    contacts.add(arrayCount,contact);

                    Contact contact1 = new Contact();
                    contact.setViewType(2);
                    contacts.add(3,contact);

                    recyclerView.setAdapter(contactAdapter);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
                Log.e("MainActivity", "Server error response::" + error);

        }
    });
    RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
    jsonRequest.setRetryPolicy(new DefaultRetryPolicy(ConstantInt.INITIAL_TIMEOUT_MS, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    requestQueue.add(jsonRequest);
}
/**
 * Method is called to send server request for manual deals.
 */
public void sendRequesttoServerForMoreDeals() {

    JSONObject jsonObject = new JSONObject();
    String dealListUrl = "http://156.222.16.1156:8985/ireward/rest/json/metallica";
    JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, dealListUrl.trim(), jsonObject, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            Log.e("MainActivity", "Server success response::" + response);
            String resultCode = "resultcode";
            try {
                int nResultCodeFromServer = Integer.parseInt(response.getString(resultCode.trim()));
                if (nResultCodeFromServer == ConstantInt.TRANSACTION_SUCCESS) {
                    JSONArray getJsonArray = response.optJSONArray(CResponseKey.DEAL_ARRAY.trim());
                    for (int i = 0; i < getJsonArray.length(); i++) {
                        try {
                            JSONObject getJsonObj = getJsonArray.getJSONObject(i);
                            contact = new Contact();
                            contact.setEmail(getJsonObj.getString(CResponseKey.DEAL_NAME.trim()));
                            contact.setPhone(getJsonObj.getString(CResponseKey.DEAL_DETAIL.trim()));
                            contact.setViewType(0);
                            contacts.add(contact);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                    contactAdapter.notifyDataSetChanged();
                    contactAdapter.setLoaded();
                    int arrayCount = getJsonArray.length();
                    Log.e("Mainactivity", "ArrayCount::" + arrayCount);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("MainActivity", "Server error response::" + error);

        }
    });
    RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
    jsonRequest.setRetryPolicy(new DefaultRetryPolicy(ConstantInt.INITIAL_TIMEOUT_MS, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    requestQueue.add(jsonRequest);
}

适配器代码

 private OnLoadMoreListener onLoadMoreListener;
private boolean isLoading;
private Context activity;
private List<Contact> contacts;
private int visibleThreshold = 5;
private int lastVisibleItem, totalItemCount;

public ContactAdapter(RecyclerView recyclerView, List<Contact> contacts, Context activity) {
    this.contacts = contacts;
    this.activity = activity;

    final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
    recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            totalItemCount = linearLayoutManager.getItemCount();
            lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
            if (!isLoading && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
                if (onLoadMoreListener != null) {
                    onLoadMoreListener.onLoadMore();
                }
                isLoading = true;
            }
        }
    });
}

public void setOnLoadMoreListener(OnLoadMoreListener mOnLoadMoreListener) {
    this.onLoadMoreListener = mOnLoadMoreListener;
}

@Override
public int getItemViewType(int position) {
   return contacts.get(position).getViewType();
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    RecyclerView.ViewHolder viewHolder = null;
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    switch (viewType) {
        case 0:
            View v = inflater.inflate(R.layout.item_recycler_view_row, parent, false);
            viewHolder = new UserViewHolder(v);
            break;
        case 1:
            View v1 = inflater.inflate(R.layout.item_loading, parent, false);
            viewHolder = new LoadingViewHolder(v1);
            break;
        case 2:
            View view = inflater.inflate(R.layout.add, parent, false);
            viewHolder = new AdView(view);
            break;
    }
    return viewHolder;

}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    switch (holder.getItemViewType()){
        case 0:
            Contact contact = contacts.get(position);
            UserViewHolder userViewHolder = (UserViewHolder) holder;
            userViewHolder.phone.setText(contact.getEmail());
            userViewHolder.email.setText(contact.getPhone());

            break;
        case 1:
            LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder;
            loadingViewHolder.progressBar.setIndeterminate(true);
            break;
        case 2 :
            AdView adView = (AdView) holder;
            adView.textView.setText("Ad");
            break;
    }

}

@Override
public int getItemCount() {
    return contacts.size();
}

public void setLoaded() {
    isLoading = false;
}

private class LoadingViewHolder extends RecyclerView.ViewHolder {
    public ProgressBar progressBar;

    public LoadingViewHolder(View view) {
        super(view);
        progressBar = (ProgressBar) view.findViewById(R.id.progressBar1);
    }
}

private class UserViewHolder extends RecyclerView.ViewHolder {
    public TextView phone;
    public TextView email;

    public UserViewHolder(View view) {
        super(view);
        phone = (TextView) view.findViewById(R.id.txt_phone);
        email = (TextView) view.findViewById(R.id.txt_email);
    }
}

private class AdView extends RecyclerView.ViewHolder {
    TextView textView;
    public AdView(View view) {
        super(view);
        textView = (TextView) view.findViewById(R.id.text);
    }
}

0 个答案:

没有答案