package com.gh.gamecenter.adapter; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.widget.RecyclerView; import android.text.Html; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.DiskBasedCache; import com.gh.base.AppController; import com.gh.common.constant.Config; import com.gh.common.util.ConcernContentUtils; import com.gh.common.util.DataUtils; import com.gh.common.util.DisplayUtils; import com.gh.common.util.GzipUtils; import com.gh.common.util.NewsUtils; import com.gh.common.util.PostCommentUtils; import com.gh.common.util.Utils; import com.gh.common.view.CardLinearLayout; import com.gh.gamecenter.MessageDetailActivity; import com.gh.gamecenter.NewsDetailActivity; import com.gh.gamecenter.R; import com.gh.gamecenter.ShareCardActivity; import com.gh.gamecenter.ShareCardPicActivity; import com.gh.gamecenter.WebActivity; import com.gh.gamecenter.adapter.viewholder.CommentHeadViewHolder; import com.gh.gamecenter.adapter.viewholder.CommentViewHolder; import com.gh.gamecenter.adapter.viewholder.FooterViewHolder; import com.gh.gamecenter.adapter.viewholder.NewsDigestViewHolder; import com.gh.gamecenter.db.CommentDao; import com.gh.gamecenter.db.VoteDao; import com.gh.gamecenter.db.info.VoteInfo; import com.gh.gamecenter.entity.CommentEntity; import com.gh.gamecenter.entity.ConcernEntity; import com.gh.gamecenter.manager.DataCollectionManager; import com.gh.gamecenter.manager.VisitManager; import com.gh.gamecenter.volley.extended.JsonArrayExtendedRequest; import com.gh.gamecenter.volley.extended.JsonObjectExtendedRequest; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.lang.reflect.Type; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; /** * Created by khy on 2016/11/8. * 消息详情-数据适配器 */ public class MessageDetailAdapter extends RecyclerView.Adapter { private Context mContext; private ConcernEntity mConcernEntity; private List mHotCommentList; private List mNormalCommentList; private VoteDao mVoteDao; private CommentDao mCommentDao; private SharedPreferences sp; private String userName; //用户名 private String userIcon; //用户icon private boolean isOver; private boolean isLoading; private boolean isNetworkError; private static final int ITEM_TOP = 100; private static final int ITEM_TITLE = 101; private static final int ITEM_COMMENT = 102; private static final int ITEM_FOOTER = 103; public MessageDetailAdapter(MessageDetailActivity context, CommentDao commentDao) { this.mContext = context; mVoteDao = new VoteDao(context); mCommentDao = commentDao; sp = context.getSharedPreferences(Config.PREFERENCE, Context.MODE_PRIVATE); userName = sp.getString("user_name", null); userIcon = sp.getString("user_icon", null); isOver = false; isLoading = false; isNetworkError = false; mHotCommentList = new ArrayList<>(); mNormalCommentList = new ArrayList<>(); mConcernEntity = (ConcernEntity) AppController.get("ConcernEntity", true); addHotComment(0); } private void addHotComment(int offset) { String hotCommentUrl = Config.COMMENT_HOST + "article/" + mConcernEntity.getId() + "/comment?order=hot&limit=10&offset=" + offset; JsonArrayExtendedRequest request = new JsonArrayExtendedRequest(hotCommentUrl, new Response.Listener() { @Override public void onResponse(JSONArray response) { Type listType = new TypeToken>() {}.getType(); Gson gson = new Gson(); List list = gson.fromJson(response.toString(), listType); if (list.size() != 0) { mHotCommentList.clear(); mHotCommentList.addAll(list); notifyDataSetChanged(); } addNormalComment(mNormalCommentList.size()); // 考虑到断网刷新问题 } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { addNormalComment(mNormalCommentList.size()); } }); AppController.addToRequestQueue(request); } public void addNormalComment(int offset) { isLoading = true; String commentUrl = Config.COMMENT_HOST + "article/" + mConcernEntity.getId() + "/comment?limit=10&offset=" + offset; JsonArrayExtendedRequest request = new JsonArrayExtendedRequest(commentUrl, new Response.Listener() { @Override public void onResponse(JSONArray response) { isLoading = false; Type listType = new TypeToken>() {}.getType(); Gson gson = new Gson(); List list = gson.fromJson(response.toString(), listType); if (list.size() < 10) { isOver = true; } if (list.size() != 0) { mNormalCommentList.addAll(list); } notifyDataSetChanged(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { isLoading = false; isNetworkError = true; notifyDataSetChanged(); } }); AppController.addToRequestQueue(request); } @Override public int getItemViewType(int position) { int index; if (mHotCommentList.size() == 0) { index = 1; } else { index = 2; } if (position == 0 && mConcernEntity != null) { return ITEM_TOP; } else if (mHotCommentList.size() != 0 && position == 1 || mNormalCommentList.size() != 0 && mHotCommentList.size() + index == position ) { return ITEM_TITLE; } else if (getItemCount() == position + 1) { return ITEM_FOOTER; } return ITEM_COMMENT; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view; switch (viewType) { case ITEM_TOP: view = LayoutInflater.from(mContext).inflate(R.layout.news_digest_item, parent, false); return new NewsDigestViewHolder(view); case ITEM_TITLE: view = LayoutInflater.from(mContext).inflate(R.layout.comment_head_item, parent, false); return new CommentHeadViewHolder(view); case ITEM_COMMENT: view = LayoutInflater.from(mContext).inflate(R.layout.comment_item, parent, false); return new CommentViewHolder(view); case ITEM_FOOTER: view = LayoutInflater.from(mContext).inflate(R.layout.refresh_footerview, parent, false); return new FooterViewHolder(view); default: return null; } } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { if (holder instanceof NewsDigestViewHolder) { initNewsDigestViewHolder((NewsDigestViewHolder) holder); } else if (holder instanceof CommentViewHolder) { initCommentViewHolder((CommentViewHolder) holder, position); } else if (holder instanceof FooterViewHolder) { initFooterViewHolder((FooterViewHolder) holder); } else if (holder instanceof CommentHeadViewHolder) { ((CardLinearLayout) holder.itemView).setmTop(DisplayUtils.dip2px(mContext, 4)); if (mHotCommentList.size() != 0 && position == 1) { ((CommentHeadViewHolder) holder).commentHeadTitleTv.setText("热门评论"); } else { ((CommentHeadViewHolder) holder).commentHeadTitleTv.setText("最新评论"); } } } @Override public int getItemCount() { int itemCount = 0; if (mHotCommentList.size() != 0) { itemCount = itemCount + mHotCommentList.size() + 1; } if (mNormalCommentList.size() != 0) { itemCount = itemCount + mNormalCommentList.size() + 1; } if (mConcernEntity != null) { itemCount = itemCount + 1; } return itemCount + 1; } private void initFooterViewHolder(final FooterViewHolder viewHolder) { LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); viewHolder.itemView.setLayoutParams(params); if (!isOver) { viewHolder.hint.setText("加载中..."); viewHolder.loading.setVisibility(View.VISIBLE); } else if (isNetworkError || mNormalCommentList.size() == 0 && mHotCommentList.size() == 0) { viewHolder.loading.setVisibility(View.GONE); params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DisplayUtils.dip2px(mContext, 185)); if (isNetworkError) { viewHolder.hint.setText("网络错误,点击重试!"); } else { viewHolder.itemView.setLayoutParams(params); viewHolder.hint.setText("目前还没有评论"); } } else { viewHolder.hint.setText("没有更多评论啦.."); viewHolder.loading.setVisibility(View.GONE); } viewHolder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (isNetworkError) { isNetworkError = false; viewHolder.loading.setVisibility(View.VISIBLE); viewHolder.hint.setText("加载中..."); addHotComment(0); } } }); } private void initNewsDigestViewHolder(NewsDigestViewHolder viewHolder) { ((CardLinearLayout) viewHolder.itemView).setmTop(DisplayUtils.dip2px(mContext, 8)); ((CardLinearLayout) viewHolder.itemView).setmBottom(DisplayUtils.dip2px(mContext, 4)); if (mConcernEntity.getViews() != 0) { viewHolder.read.setText(String.format(Locale.getDefault(), "阅读 %d", mConcernEntity.getViews())); } if (mConcernEntity.getCommentnum() != 0) { if (mConcernEntity.getCommentnum() > 999) { viewHolder.commentnum.setText(R.string.thousand); } else { viewHolder.commentnum.setText(String.valueOf(mConcernEntity.getCommentnum())); } } if (mConcernEntity.getLink() != null) { viewHolder.link.setImageResource(R.drawable.link_iv); } else { viewHolder.link.setImageResource(R.drawable.concern_message_icon); } if (mConcernEntity.getBrief() != null) { viewHolder.content.setText(Html.fromHtml(mConcernEntity.getBrief())); viewHolder.content.setMaxLines(100); } else { viewHolder.content.setText(Html.fromHtml(mConcernEntity.getContent())); viewHolder.content.setMaxLines(5); } if (mConcernEntity.getImg().size() == 0) { viewHolder.imgLayout.setVisibility(View.GONE); viewHolder.imgLayout.removeAllViews(); } else { viewHolder.imgLayout.setVisibility(View.VISIBLE); viewHolder.imgLayout.removeAllViews(); ConcernContentUtils.addContentPic(mContext.getResources().getDisplayMetrics().widthPixels - DisplayUtils.dip2px(mContext, 34), viewHolder.imgLayout, mConcernEntity.getImg(), mContext); } viewHolder.thumb.setImageURI(mConcernEntity.getGameIcon()); viewHolder.title.setText(mConcernEntity.getGameName()); NewsUtils.setNewsPublishOn(viewHolder.time, mConcernEntity.getTime()); viewHolder.share.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String shareContent; if (mConcernEntity.getBrief() != null) { shareContent = mConcernEntity.getBrief(); } else { shareContent = mConcernEntity.getContent(); } if (mConcernEntity.getImg() != null && mConcernEntity.getImg().size() > 0) { Intent intent = new Intent(mContext, ShareCardPicActivity.class); Bundle bundle = new Bundle(); bundle.putString("gameName", mConcernEntity.getGameName()); bundle.putString("gameIconUrl", mConcernEntity.getGameIcon()); bundle.putString("shareContent", shareContent); bundle.putStringArrayList("shareArrImg", (ArrayList) mConcernEntity.getImg()); intent.putExtras(bundle); mContext.startActivity(intent); } else { Intent intent = new Intent(mContext, ShareCardActivity.class); Bundle bundle = new Bundle(); bundle.putString("gameName", mConcernEntity.getGameName()); bundle.putString("gameIconUrl", mConcernEntity.getGameIcon()); bundle.putString("shareContent", shareContent); intent.putExtras(bundle); mContext.startActivity(intent); } } }); viewHolder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Map kv = new HashMap<>(); kv.put("名字", mConcernEntity.getTitle()); DataUtils.onEvent(mContext, "点击", "消息详情", kv); Map map = new HashMap<>(); map.put("page", "消息详情"); map.put("news", mConcernEntity.getTitle()); map.put("news_id", mConcernEntity.getId()); DataCollectionManager.onEvent(mContext, "click-item", map); // 统计阅读量 statNewsViews(mConcernEntity.getId()); if (mConcernEntity.getLink() != null) { Intent intent = new Intent(mContext, WebActivity.class); intent.putExtra("url", mConcernEntity.getLink()); intent.putExtra("gameName", mConcernEntity.getGameName()); mContext.startActivity(intent); } else { Intent intent = new Intent(mContext, NewsDetailActivity.class); intent.putExtra("newsId", mConcernEntity.getId()); intent.putExtra("entrance", "(消息详情)"); mContext.startActivity(intent); } } }); } private void initCommentViewHolder(final CommentViewHolder holder, int position) { int index; if (mHotCommentList.size() == 0) { index = 2; } else { index = 3; } int commentPosition = 0;// boolean isHotComment = false; //区分热门评论和最新评论 - 修改缓存链接 CommentEntity commentEntity = null; // 初始化数据 if (mHotCommentList.size() != 0 && mHotCommentList.size() > position -2) { commentEntity = mHotCommentList.get(position -2); isHotComment = true; if (mHotCommentList.size() == position - 1) { ((CardLinearLayout) holder.itemView).setmBottom(DisplayUtils.dip2px(mContext, 4)); } else { ((CardLinearLayout) holder.itemView).setmBottom(0); } } else if (mNormalCommentList.size() != 0 && mNormalCommentList.size() > position - mHotCommentList.size() - index) { commentPosition = position - mHotCommentList.size() - index; commentEntity = mNormalCommentList.get(position - mHotCommentList.size() - index); isHotComment = false; if ( mNormalCommentList.size() == position - mHotCommentList.size() - index + 1) { ((CardLinearLayout) holder.itemView).setmBottom(DisplayUtils.dip2px(mContext, 4)); } else { ((CardLinearLayout) holder.itemView).setmBottom(0); } } if (commentEntity == null) { return; } holder.commentContentTv.setText(commentEntity.getContent()); holder.commentLikeCountTv.setTextColor(mContext.getResources().getColor(R.color.hint)); holder.commentLikeIv.setImageResource(R.drawable.comment_like_unselect); if (commentEntity.getVote() == 0) { holder.commentLikeCountTv.setVisibility(View.GONE); } else { // 检查是否已点赞 if (mVoteDao.isVote(commentEntity.getId()) && commentEntity.getVote() >= 1) { holder.commentLikeCountTv.setTextColor(mContext.getResources().getColor(R.color.theme)); holder.commentLikeIv.setImageResource(R.drawable.comment_like_select); } holder.commentLikeCountTv.setVisibility(View.VISIBLE); holder.commentLikeCountTv.setText(String.valueOf(commentEntity.getVote())); } //检查是否是自身评论 if (userName != null && userIcon != null && !userIcon.isEmpty()&& !userIcon.isEmpty() && mCommentDao.isMyComment(commentEntity.getId())){ holder.commentUserNameTv.setText(sp.getString("user_name", null)); holder.commentUserIconDv.setImageURI(sp.getString("user_icon", null)); } else { holder.commentUserNameTv.setText(commentEntity.getUser().getName()); if(commentEntity.getUser().getIcon().isEmpty()) { holder.commentUserIconDv.setImageURI("res:///" + R.drawable.user_default_icon_comment); } else { holder.commentUserIconDv.setImageURI(commentEntity.getUser().getIcon()); } } SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd", Locale.getDefault()); try { long today = format.parse(format.format(new Date())).getTime(); long day = commentEntity.getTime() * 1000; if (day >= today && day < today + 86400 * 1000) { long min = new Date().getTime()/1000 - day/1000; int hour = (int) (min/ (60 * 60)); if (hour == 0) { if (min < 60) { holder.commentTimeTv.setText("刚刚"); } else { holder.commentTimeTv.setText(String.format(Locale.getDefault(), "%d分钟前", (int) (min / 60))); } } else { holder.commentTimeTv.setText(String.format(Locale.getDefault(), "%d小时前", hour)); } } else if (day >= today - 86400 * 1000 && day < today) { format.applyPattern("HH:mm"); holder.commentTimeTv.setText("昨天 "); } else { format.applyPattern("yyyy-MM-dd"); holder.commentTimeTv.setText(format.format(day)); } } catch (ParseException e) { e.printStackTrace(); format.applyPattern("yyyy-MM-dd"); holder.commentTimeTv.setText(format.format(commentEntity.getTime() * 1000)); } final CommentEntity finalCommentEntity = commentEntity; final boolean finalIsHotComment = isHotComment; final int finalCommentPosition = commentPosition; holder.commentLikeIv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (holder.commentLikeCountTv.getCurrentTextColor() == mContext.getResources().getColor(R.color.theme)) { Utils.toast(mContext, "已经点过赞啦!"); return; } finalCommentEntity.setVote(finalCommentEntity.getVote() + 1); PostCommentUtils.addCommentVoto(mContext, finalCommentEntity.getId()); holder.commentLikeCountTv.setTextColor(mContext.getResources().getColor(R.color.theme)); holder.commentLikeIv.setImageResource(R.drawable.comment_like_select); holder.commentLikeCountTv.setText(String.valueOf(finalCommentEntity.getVote())); holder.commentLikeCountTv.setVisibility(View.VISIBLE); mVoteDao.add(new VoteInfo(finalCommentEntity.getId())); int index = (finalCommentPosition /10) * 10; //获取需要修改缓存的链接 String cacheUrl; if (finalIsHotComment) { cacheUrl = Config.COMMENT_HOST + "article/" + mConcernEntity.getId() + "/comment?order=hot&limit=" + 10 + "&offset=" + 0; // 热门评论固定链接 } else { cacheUrl = Config.COMMENT_HOST + "article/" + mConcernEntity.getId() + "/comment?limit=" + 10 + "&offset=" + index; } modifyVolleyCache(finalCommentEntity.getId(), cacheUrl); //修改缓存 } }); } private void statNewsViews(final String news_id) { String url = Config.DATA_HOST + "news/stat?news_id=" + news_id; JsonObjectExtendedRequest request = new JsonObjectExtendedRequest( Request.Method.POST, url, new Response.Listener() { @Override public void onResponse(JSONObject response) { try { if ("success".equals(response.getString("status"))) { mConcernEntity.setViews(mConcernEntity.getViews() + 1); notifyItemChanged(0); // 更新okhttp缓存数据 VisitManager.updateOkhttpCache(mConcernEntity.getId()); } } catch (JSONException e) { e.printStackTrace(); } } }, null); request.setShouldCache(false); AppController.addToRequestQueue(request); } private static final String DEFAULT_CACHE_DIR = "volley"; private void modifyVolleyCache(String id, String url) { if (url == null) { return; } File cacheDir = new File(mContext.getCacheDir(), DEFAULT_CACHE_DIR); DiskBasedCache cache = new DiskBasedCache(cacheDir); byte[] data = cache.getData(url); if (data != null) { try { JSONArray jsonArray = new JSONArray(new String(GzipUtils.decompressBytes(data))); JSONObject jsonObject; for (int i = 0, size = jsonArray.length(); i < size; i++) { jsonObject = jsonArray.getJSONObject(i); if (jsonObject.getString("_id").equals(id)) { jsonObject.put("vote", jsonObject.getInt("vote") + 1); break; } } Utils.log(jsonArray.toString()); cache.modify(url, GzipUtils.compressBytes(jsonArray.toString().getBytes())); } catch (JSONException e) { e.printStackTrace(); } } else { Utils.log("modifyVolleyCache is null"); } } public String getNewsId() { return mConcernEntity.getId(); } public ConcernEntity getConcernEntity() { return mConcernEntity; } public boolean isLoading() { return isLoading; } // 往位置0添加评论 public void addNormalComment(CommentEntity commentEntity) { mNormalCommentList.add(0, commentEntity); } public void addCommentCount() { mConcernEntity.setCommentnum(mConcernEntity.getCommentnum() + 1); notifyItemChanged(0); } public int getHotCommentListSize() { int index = 0; if (mHotCommentList.size() != 0) { index = mHotCommentList.size() + 1; } return index; } public boolean isOver() { return isOver; } }