Android仿人人客户端(v5.7.1)——新鲜事之状态

                                                                 转载请标明出处:http://blog.csdn.net/android_ls/article/details/8815622
声明:仿人人项目,所用所有图片资源都来源于其它Android移动应用,编写本应用的目的在于学习交流,如涉及侵权请告知,我会及时换掉用到的相关图片。

        有关仿人人的文章是一个系列文章,不明白的请翻阅前面的博文。这一篇和大家聊一聊,有关新鲜事的获取和以列表的形式展示。

一、新鲜事的类别,各个数字值所代表的的含义:

         10 更新状态的新鲜事; 11 page更新状态的新鲜事; 20 发表日志的新鲜事; 21 分享日志的新鲜事; 22 page发表日志的新鲜事;23 page分享日志的新鲜事; 30 上传照片的新鲜事; 31 page上传照片的新鲜事; 32 分享照片的新鲜事; 33 分享相册的新鲜事; 34 修改头像的新鲜事; 35 page修改头像的新鲜事; 36 page分享照片的新鲜事;40 为好友的新鲜事;41 为page粉丝的新鲜事;50 分享视频的新鲜事;51 分享链接的新鲜事;52 分享音乐的新鲜事; 53 page分享视频的新鲜事;54 page分享链接的新鲜事; 55 page分享音乐的新鲜事。

二、构建请求参数,发起网络请求。

       构建请求参数,默认获取所有类别的新鲜事,取第一页(每一页记录数,默认值为30)。

        // 所有类别的新鲜事
        String freshNewsAll = "10,11,20,21,22,23,31,32,33,34,35,36,40,41,50,51,52,53,54,55";
        
        Map<String, String> parameter = new HashMap<String, String>();
        parameter.put("v", "1.0"); // API的版本号,固定值为1.0 
        parameter.put("access_token", accessToken); // OAuth2.0验证授权后获得的token。
        parameter.put("format", "JSON"); // 返回值的格式。请指定为JSON或者XML
        parameter.put("call_id", "2.0"); // 请求队列号
        parameter.put("method", "feed.get");
        parameter.put("type", freshNewsAll); // 新鲜事的类别,多个类型以逗号分隔,type列表 
        parameter.put("uid", ""); // 支持传入当前用户的一个好友ID,表示获取此好友的新鲜事,如果不传,默认为获取当前用户的新鲜事 
        parameter.put("page", page + ""); // 支持分页,指定页号,页号从1开始,默认值为1 
        parameter.put("count", pageCount + ""); // 支持分页,每一页记录数,默认值为30,最大50 

        发起网络请求

        AsyncHttpsPost asyncHttpsPost = new AsyncHttpsPost(Constant.API_SERVER_URL, parameter, new ParseCallback() {
            
            @Override
            public Object parse(String json) throws JSONException {
                LogUtil.i("EveryoneActivity", "json = " + json);
                
                return null;
            }
        }, new ResultCallback() {
            
            @Override
            public void onSuccess(Object obj) {
                // TODO Auto-generated method stub
                
            }
            
            @Override
            public void onFail(int errorCode) {
                // TODO Auto-generated method stub
                
            }
        });
        
        mDefaultThreadPool.execute(asyncHttpsPost);
        mAsyncRequests.add(asyncHttpsPost);

          注:Constant.API_SERVER_URL的值为https://api.renren.com/restserver.do(人人服务器URL(API Server URL))
       网络请求返回的JSON字符串

     [
         {
             "actor_id":600038849,
             "actor_type":"page",
             "source_id":4680225717,
             "feed_type":11,
             "attachment":[],
             "post_id":21964215624,
             "headurl":"http:\/\/hdn.xnimg.cn\/photos\/hdn221\/20110212\/1700\/h_head_jMyd_4a320001f9f62f75.jpg",
             "message":"【北上广墓位开始限售 市民为买墓半夜排队】北京、上海、广州等大型城市很多公墓都出现了墓地紧缺,开始限售墓位,有上海市民曾经半夜赶到了某陵园等候购买墓位,为了买一个位置去年几乎忙了半年。民政部称,全国大部分的省份现有的墓穴都将在10年内用完。",
             "title":"【北上广墓位开始限售 市民为买墓半夜排队】北京、上海、广州等大型城市很多公墓都出现了墓地紧缺,开始限售墓位,有上海市民曾经半夜赶到了某陵园等候购买墓位,为了买一个位置去年几乎忙了半年。民政部称,全国大部分的省份现有的墓穴都将在10年内用完。",
             "update_time":"2013-04-03 18:19:46",
             "likes":{"friend_count":0,"user_like":0,"total_count":0},
             "name":"折翼の天使",
             "prefix":"【北上广墓位开始限售 市民为买墓半夜排队】北京、上海、广州等大型城市很多公墓都出现了墓地紧缺,开始限售墓位,有上海市民曾经半夜赶到了某陵园等候购买墓位,为了买一个位置去年几乎忙了半年。民政部称,全国大部分的省份现有的墓穴都将在10年内用完。",
             "comments":
             {
                 "count":19,
                 "comment":
                 [
                      {
                          "uid":257105823,
                          "comment_id":14762714581,
                          "time":"2013-04-03 18:21",
                          "text":"\"活着没屋住 死了没坑埋 \"",
                          "name":"接实 洗髓",
                          "headurl":"http:\/\/hdn.xnimg.cn\/photos\/hdn221\/20130331\/2125\/h_tiny_itUR_b7e600000fb5113e.jpg"
                        },
                        {
                            "uid":511348598,
                            "comment_id":14768302556,
                            "time":"2013-04-04 19:28",
                            "text":"\"你能受的聊吗\"",
                            "name":"田思佳",
                            "headurl":"http:\/\/hdn.xnimg.cn\/photos\/hdn521\/20130222\/0835\/h_tiny_hEVJ_c680000009df111a.jpg"
                        }
                 ]
              }         
           }
       ]

           构建实体类,对返回的JSON字符串进行解析。(这里不明白的可以查看我的这篇Android仿人人客户端(v5.7.1)——通过HTTPS协议的POST方式获取用户的基本信息

package com.everyone.android.entity;

import java.util.ArrayList;

/**
 * 功能描述:新鲜事信息实体类
 * @author android_ls
 *
 */
public class FreshNews {

    private int post_id; // 表示新鲜事的id 

    private int source_id; //  表示新鲜事内容主体的id,例如日志id、相册id和分享id等等 

    private int feed_type; // 表示新鲜事类型

    private String update_time; // 表示新鲜事更新时间 

    private int actor_id; //  表示新鲜事用户的id 

    private String name; // 表示新鲜事用户的姓名 

    private String actor_type; //  表示新鲜事发起者的类型,目前有“user”,“page”。user代表人人网用户新鲜事,page代表公共主页新鲜事。 

    private int headurl; //  表示新鲜事用户的头像 

    private String prefix; // 表示新鲜事内容的前缀

    private String message; // 表示新鲜事用户自定义输入内容,状态 

    private String title; //  表示新鲜事的主题内容  

    private String href; //  表示新鲜事主题的相关链接 

    private String description; //  表示新鲜事的具体内容 

    private ArrayList<Attachment> attachment; //  表示新鲜事中包含的媒体内容,例如照片、视频等 

    private Like likes;// 表示赞相关的信息 

    private Source source; // 应该是来源信息 [官方文档中的解释:表示赞中好友的数量(不甚理解,什么意思?)]

    private Comments comments; //  表示新鲜事中包含的评论内容,目前返回最新和最早的评论 

    private Place place; // 表示新鲜事发生的地点 

}

        新鲜事中包含的媒体(照片、视频等)信息实体类

package com.everyone.android.entity;

/**
 * 功能描述:新鲜事中包含的媒体(照片、视频等)信息实体类 
 * @author android_ls
 *
 */
public class Attachment {

    private String href; // 表示媒体内容的链接地址feed_media子节点 

    private String media_type; // 表示媒体内容的类型,目前有“photo”, “album”, “link”, “video”, “audio”, “status” feed_media子节点 

    private String scr; //  表示媒体内容的原地址 feed_media子节点 

    private String raw_src; // media_type为“photo”时特有,代表未加工过的原图URL。 

    private String content; // 表示媒体文本相关内容,例如:media_type为“status”代表状态的内容;media_type为“photo”代表照片的描述信息。 

    private int media_id; //  表示媒体内容的id,例如相片的id feed_media子节点 

    private int owner_id; //  表示媒体内容的所有者idfeed_media子节点 

}

        评论信息数据集实体类

package com.everyone.android.entity;

import java.util.ArrayList;

/**
 * 功能描述:评论信息
 * @author android_ls
 *
 */
public class Comments {

    private int count; //  表示评论的数量 comments子节点 

    private ArrayList<Comment> comment; //  表示评论的具体内容comments子节点 

}

        。。。

        剩余的几个实体类的描述就不贴代码了,主要的实体类的字段描述如上,至于生成get和set方法的事,我想大家都熟练(真正的体力活,呵呵)就不贴代码,要不篇幅过于长了。实体类是参考官方的返回参数说明创建,地址:http://wiki.dev.renren.com/wiki/Feed.get,我们这里关于JSON字符串解析的事和前面的处理一样,使用谷歌提供的Gson进行解析。

        new ParseCallback() {
            
            @Override
            public Object parse(String json) throws JSONException {
                LogUtil.i(TAG, "json = " + json);
                
                Gson gson = new Gson();
                java.lang.reflect.Type type = new TypeToken<LinkedList<FreshNews>>() {}.getType();
                LinkedList<FreshNews> freshNewsList = gson.fromJson(json, type);
                
                LogUtil.i(TAG, "freshNewsList = " + freshNewsList.size());
                
                return freshNewsList;
            }
        }

           运行程序,耐心等待,过一会程序崩溃,LogCat打印LOG如下:

            仔细查看发现是JSON解析出错了,解决思路:检查你写的实体类的字段是否与人人官方给出的字段类型一致,我仔细对比了一遍,没错啊。之后到Google的Android官网查看关于GSON的使用有什么限制,发现原来使用GSON解析JSON时,对集合的类型是有限制的。将所有的实体类中的集合类型ArrayList修改为LinkedList,问题解决。

三、使用ListView展示数据

           1、布局文件(fresh_news.xml)如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFFFFF"
    android:orientation="vertical" >

    <com.everyone.android.widget.TopMenuNavbar
        android:id="@+id/rl_top_menu_navbar"
        style="@style/top_navbar" />

    <include
        android:id="@+id/loading"
        layout="@layout/loading_progressbar" />

    <include
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        layout="@layout/listview" />

</LinearLayout>

       include 的布局(listview.xml)文件如下:

<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/listview"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#00000000"
    android:cacheColorHint="#00000000"
    android:divider="@drawable/v5_0_1_newsfeed_divider"
    android:listSelector="@null" />

     2、初始化ListView,设置数据适配器

        mListView = (ListView) freshNewsViewRoot.findViewById(R.id.listview);
        mFreshNewsAdapter = new FreshNewsAdapter(mActivity, mFreshNewsList);
        mListView.setAdapter(mFreshNewsAdapter);

       3、数据适配器

           a. ListView的Item布局文件( fresh_news_list_item.xml),目前只处理了基本信息和新鲜事状态相关的。

<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/fresh_news_list_item_selector" >

    <!-- 头像 -->

    <ImageView
        android:id="@+id/iv_user_image"
        android:layout_width="43.0dip"
        android:layout_height="43.0dip"
        android:layout_marginLeft="10.0dip"
        android:layout_marginTop="8.0dip"
        android:saveEnabled="true"
        android:src="@drawable/v5_0_1_widget_default_head" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dip"
        android:layout_marginRight="8dip"
        android:layout_marginTop="8dip"
        android:layout_toRightOf="@+id/iv_user_image"
        android:orientation="vertical"
        android:paddingBottom="8dip" >

        <!-- 昵称 -->

        <TextView
            android:id="@+id/tv_nickname"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#ff005092"
            android:textSize="16sp" />
        <!-- 内容 -->

        <TextView
            android:id="@+id/tv_content"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="5.0dip"
            android:textColor="#000000"
            android:textSize="15.0sp" />

        <!-- 更新状态 -->

        <LinearLayout
            android:id="@+id/ll_update_status"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/tv_nickname"
            android:layout_below="@+id/tv_content"
            android:layout_marginTop="8dip"
            android:orientation="horizontal"
            android:visibility="gone" >

            <View
                android:layout_width="2dip"
                android:layout_height="fill_parent"
                android:background="#20333333" />

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dip"
                android:orientation="vertical" >

                <TextView
                    android:id="@+id/tv_status_name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textColor="#ff005092"
                    android:textSize="14sp" />

                <TextView
                    android:id="@+id/tv_status_content"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dip"
                    android:textColor="#ff888888"
                    android:textSize="13sp" />
            </LinearLayout>
        </LinearLayout>

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" >

            <!-- 时间 -->

            <TextView
                android:id="@+id/tv_published"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="8.0dip"
                android:drawablePadding="3dip"
                android:textColor="#ff666666"
                android:textSize="12.0sp" />

            <!-- 来源 -->

            <TextView
                android:id="@+id/tv_source"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="15dip"
                android:layout_marginTop="8.0dip"
                android:layout_toRightOf="@+id/tv_published"
                android:textColor="#ff666666"
                android:textSize="13.0sp" />
        </RelativeLayout>

        <!-- 用于显示图片 -->

        <ImageView
            android:id="@+id/iv_content_picture"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5.0dip"
            android:scaleType="fitXY"
            android:src="@drawable/pic_default"
            android:visibility="gone" />

        <!-- 评论信息 -->

        <LinearLayout
            android:id="@+id/ll_comments_content"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="7.0dip"
            android:background="@drawable/fresh_news_popup"
            android:orientation="vertical"
            android:padding="10dip"
            android:visibility="gone" />
    </LinearLayout>

</RelativeLayout>

        b. getView()方法里面的处理,说下关键的几点:

            设置姓名和图像

       final FreshNews freshNews = mFreshNewsList.get(position);
        
        // 姓名
        holder.text1.setText(freshNews.getName());

        // 加载图像
        String headurl = freshNews.getHeadurl();
        LogUtil.i(TAG, "headurl = " + headurl);
        if (!TextUtils.isEmpty(headurl)) {
            int widthPx = DensityUtil.dip2px(mActivity, 43);
            ImageInfo imgInfo = new ImageInfo(holder.imageView1, headurl, widthPx, widthPx);
            mImageLoader.displayImage(imgInfo);
        }

              几个比较难区分的字段

    /* 下面这几个字段比较难区分,人人的官方文档里描述的不是很清楚,
         * 比如新鲜事内容的前缀在那种新鲜事类型下显示等。
         * 我的做法是与人人官方的应用对比,猜测在某种类型下,可能取得是下面的某个字段的值。
         * 猜的话,很容易搞错。
         */
        String description = freshNews.getDescription();
        LogUtil.i(TAG, "description = " + description);
        LogUtil.i(TAG, "freshNews.getMessage() = " + freshNews.getMessage());
        LogUtil.i(TAG, "freshNews.getTitle() = " + freshNews.getTitle());
        LogUtil.i(TAG, "freshNews.getPrefix() = " + freshNews.getPrefix());

             根据新鲜事类型做相应的处理

   // 用户自定义输入内容,状态 
        String message = freshNews.getMessage();
        if (!TextUtils.isEmpty(message)) {
            holder.text2.setVisibility(View.VISIBLE);
            holder.text2.setText(message);
        } else {
            holder.text2.setVisibility(View.GONE);
        }
        
        // page代表公共主页新鲜事
        int feedType = freshNews.getFeed_type();
        switch (feedType) {
        case 10: // 更新状态的新鲜事。 
        case 11: // page更新状态的新鲜事。 

            // 设置状态标识图标
            holder.text3.setCompoundDrawablesWithIntrinsicBounds(R.drawable.v5_0_1_newsfeed_status_icon, 0, 0, 0);

            // 内容的前缀
            String prefix = freshNews.getPrefix();
            if (!TextUtils.isEmpty(prefix)) {
                holder.text2.setVisibility(View.VISIBLE);
                holder.text2.setText(prefix);
            } else {
                holder.text2.setVisibility(View.GONE);
            }
            
            LinkedList<Attachment> attachment = freshNews.getAttachment();
            if (attachment != null) {
                int size = attachment.size();
                LogUtil.i(TAG, "size = " + size);
                if(size > 0){
                    holder.linearLayout2.setVisibility(View.VISIBLE);
                    for (int i = 0; i < size; i++) {
                        // 这里测试只取第一个
                        Attachment att = attachment.get(i);
                        if ("status".equals(att.getMedia_type())) {
                            LogUtil.i(TAG, "att.getContent() = " + att.getContent());
                            
                            holder.text5.setText(att.getOwner_name());
                            holder.text6.setText(att.getContent());
                            break;
                        }
                    }
                } else {
                    holder.linearLayout2.setVisibility(View.GONE);
                }
            } else {
                holder.linearLayout2.setVisibility(View.GONE);
            }

            break;
        case 20: // 发表日志的新鲜事。 
        case 22: // page发表日志的新鲜事。 
            
            break;
        case 21: // 分享日志的新鲜事。 
        case 23: // page分享日志的新鲜事。 

            break;
        case 30: // 上传照片的新鲜事。
        case 31: // page上传照片的新鲜事。  

            break;
        case 32: // 分享照片的新鲜事。 
        case 33: // 分享相册的新鲜事。  

            break;
        // ...
        default:
            break;
        }

          动态生成显示评论信息的Item

        // 动态生成显示评论信息的Item
        Comments comments = freshNews.getComments();
        if (comments != null) {
            LinkedList<Comment> commentList = comments.getComment();
            if (commentList != null) {
                holder.linearLayout1.setVisibility(View.VISIBLE);
                
                if(holder.linearLayout1.getChildCount() > 0){
                    holder.linearLayout1.removeAllViews();
                }
                
                int count = comments.getCount();
                if (count > 0) {
                    TextView tvCount = new TextView(mActivity);
                    tvCount.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
                    tvCount.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
                    tvCount.setSingleLine();
                    tvCount.setCompoundDrawablePadding(5);
                    tvCount.setPadding(0, 10, 0, 0);
                    tvCount.setText(count + "条评论");
                    tvCount.setTextColor(Color.parseColor("#ff005092"));
                    tvCount.setCompoundDrawablesWithIntrinsicBounds(R.drawable.fresh_news_comment_icon, 0, 0, 0);
                    holder.linearLayout1.addView(tvCount);
                }
                
                int size = commentList.size();
                LogUtil.i(TAG, "commentList size = " + size);
                for (int i = 0; i < size; i++) {
                    Comment comment = commentList.get(i);
                    LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

                    TextView tvContent = new TextView(mActivity);
                    tvContent.setLayoutParams(layoutParams);
                    tvContent.setTextColor(Color.BLACK);
                    tvContent.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
                    tvContent.setSingleLine();
                    tvContent.setPadding(0, 10, 0, 0);
                    tvContent.setText(comment.getName() + ":" + comment.getText());
                    holder.linearLayout1.addView(tvContent);

                    TextView tvTime = new TextView(mActivity);
                    tvTime.setTextColor(Color.GRAY);
                    tvTime.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
                    tvTime.setLayoutParams(layoutParams);
                    tvContent.setPadding(0, 5, 0, 10);
                    tvTime.setText(comment.getTime());
                    holder.linearLayout1.addView(tvTime);
                }
               
            } else {
                holder.linearLayout1.setVisibility(View.GONE);
            }
        } else {
            holder.linearLayout1.setVisibility(View.GONE);
        }

          时间与来源

     // 对获取的时间字符串的处理
        String updateTime = freshNews.getUpdate_time();
        if (!TextUtils.isEmpty(updateTime)) {
            updateTime = updateTime.substring(updateTime.indexOf("-")+1, updateTime.lastIndexOf(":"));
            updateTime = updateTime.replace("-", "月");
            updateTime = updateTime.replace(" ", "日 ");
            int index = updateTime.indexOf("0");
            if(index == 0){
                updateTime = updateTime.substring(index + 1);
            }
            
            holder.text3.setText(updateTime);
        }
        
        // 来自那种客户端
        Source source = freshNews.getSource();
        if (source != null) {
            holder.text4.setText("来自:" + source.getText());
        }

  四、运行后的效果图 

 

     点击顶部左侧的Menu

 

         更新状态的显示效果图




五、完整的代码

新鲜事视图(FreshNewsLayout)

package com.everyone.android.freshnews;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.json.JSONException;

import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.everyone.android.R;
import com.everyone.android.api.AuthTokenManager;
import com.everyone.android.callback.ParseCallback;
import com.everyone.android.callback.ResultCallback;
import com.everyone.android.entity.FreshNews;
import com.everyone.android.net.AsyncBaseRequest;
import com.everyone.android.net.AsyncHttpsPost;
import com.everyone.android.net.DefaultThreadPool;
import com.everyone.android.ui.EveryoneActivity;
import com.everyone.android.utils.Constant;
import com.everyone.android.utils.LogUtil;
import com.everyone.android.widget.TopMenuNavbar;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * 功能描述:新鲜事视图
 * @author android_ls
 */
public class FreshNewsLayout extends FrameLayout implements OnClickListener {

    /**
     * LOG打印标签
     */
    private static final String TAG = "FreshNewsLayout";

    /**
     * 顶部导航栏(工具栏)
     */
    private TopMenuNavbar topMenuNavbar;

    /**
     * 所有类别的新鲜事
     */
    private static final String FRESH_NEWS_TYPE_ALL = "10,11,20,21,22,23,31,32,33,34,35,36,40,41,50,51,52,53,54,55";

    /**
     * 每一页记录数,默认值为30,最大50 
     */
    private int pageCount = 30;

    /**
     * 当前获取第几页,默认值为1
     */
    private int page = 1;

    public TopMenuNavbar getTopMenuNavbar() {
        return topMenuNavbar;
    }

    private EveryoneActivity mActivity;

    private List<AsyncBaseRequest> mAsyncRequests;

    private DefaultThreadPool mDefaultThreadPool;

    private Handler mHandler;

    public AuthTokenManager mAuthTokenManager;

    private LinearLayout mLoadingView;

    private ListView mListView;

    private FreshNewsAdapter mFreshNewsAdapter;

    /**
     * 新鲜事信息集合
     */
    private LinkedList<FreshNews> mFreshNewsList = new LinkedList<FreshNews>();

    public FreshNewsLayout(EveryoneActivity activity) {
        super(activity);
        mActivity = activity;

        this.mAsyncRequests = activity.getAsyncRequests();
        this.mDefaultThreadPool = activity.getDefaultThreadPool();
        this.mHandler = activity.getHandler();
        this.mAuthTokenManager = activity.getAuthTokenManager();

        setupViews();
    }

    /*  public FreshNewsLayout(Context context, AttributeSet attrs) {
          super(context, attrs);
          setupViews();
      }*/

    private void setupViews() {
        final LayoutInflater mLayoutInflater = LayoutInflater.from(getContext());
        LinearLayout freshNewsViewRoot = (LinearLayout) mLayoutInflater.inflate(R.layout.fresh_news, null);
        addView(freshNewsViewRoot);

        // 加载提示进度条
        mLoadingView = (LinearLayout) freshNewsViewRoot.findViewById(R.id.loading);

        topMenuNavbar = (TopMenuNavbar) freshNewsViewRoot.findViewById(R.id.rl_top_menu_navbar);
        topMenuNavbar.mLlDownList.setOnClickListener(this);
        topMenuNavbar.mLlRefresh.setOnClickListener(this);
        topMenuNavbar.ivRightLine.setVisibility(View.GONE);
        topMenuNavbar.tvRightOperationName.setVisibility(View.GONE);

        mListView = (ListView) freshNewsViewRoot.findViewById(R.id.listview);
        mFreshNewsAdapter = new FreshNewsAdapter(mActivity, mFreshNewsList);
        mListView.setAdapter(mFreshNewsAdapter);

        // TODO 这里暂时简单的这样处理
        mListView.setOnScrollListener(new OnScrollListener() {

            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (view.getLastVisiblePosition() == view.getCount() - 1) {
                    page++;
                    getNewsAll();
                }
            }

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

            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.ll_down_list:

            break;
        case R.id.ll_refresh:

            break;
        default:
            break;
        }

    }

    /**
     * 向服务器端请求新鲜事的数据
     */
    public void getNewsAll() {
        String accessToken = mAuthTokenManager.getAccessToken();
        LogUtil.e(TAG, "accessToken = " + accessToken);

        Map<String, String> parameter = new HashMap<String, String>();
        parameter.put("v", "1.0"); // API的版本号,固定值为1.0 
        parameter.put("access_token", accessToken); // OAuth2.0验证授权后获得的token。
        parameter.put("format", "JSON"); // 返回值的格式。请指定为JSON或者XML
        parameter.put("call_id", "1.0"); // 请求队列号
        parameter.put("method", "feed.get");
        parameter.put("type", FRESH_NEWS_TYPE_ALL); // 新鲜事的类别,多个类型以逗号分隔,type列表 
        // parameter.put("uid", ""); // 支持传入当前用户的一个好友ID,表示获取此好友的新鲜事,如果不传,默认为获取当前用户的新鲜事 
        parameter.put("page", page + ""); // 支持分页,指定页号,页号从1开始,默认值为1 
        parameter.put("count", pageCount + ""); // 支持分页,每一页记录数,默认值为30,最大50 
        AsyncHttpsPost asyncHttpsPost = new AsyncHttpsPost(Constant.API_SERVER_URL, parameter, new ParseCallback() {

            @Override
            public Object parse(String json) throws JSONException {
                LogUtil.i(TAG, "json = " + json);

                Gson gson = new Gson();
                java.lang.reflect.Type type = new TypeToken<LinkedList<FreshNews>>() {
                }.getType();
                LinkedList<FreshNews> freshNewsList = gson.fromJson(json, type);

                LogUtil.i(TAG, "freshNewsList = " + freshNewsList.size());

                return freshNewsList;
            }
        }, new ResultCallback() {

            @Override
            public void onSuccess(Object obj) {
                @SuppressWarnings("unchecked")
                LinkedList<FreshNews> freshNewsList = (LinkedList<FreshNews>) obj;
                if (freshNewsList.isEmpty()) {
                    return;
                }

                mFreshNewsList.addAll(freshNewsList);

                mHandler.post(new Runnable() {

                    @Override
                    public void run() {
                        mLoadingView.setVisibility(View.GONE);
                        mFreshNewsAdapter.notifyDataSetChanged();
                    }
                });

            }

            @Override
            public void onFail(int errorCode) {
                // TODO Auto-generated method stub

            }
        });

        mDefaultThreadPool.execute(asyncHttpsPost);
        mAsyncRequests.add(asyncHttpsPost);
    }

}

新鲜事列表数据适配器(FreshNewsAdapter)

package com.everyone.android.freshnews;

import java.util.LinkedList;

import android.graphics.Color;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.everyone.android.R;
import com.everyone.android.bitmap.ImageLoader;
import com.everyone.android.entity.Attachment;
import com.everyone.android.entity.Comment;
import com.everyone.android.entity.Comments;
import com.everyone.android.entity.FreshNews;
import com.everyone.android.entity.ImageInfo;
import com.everyone.android.entity.Source;
import com.everyone.android.ui.EveryoneActivity;
import com.everyone.android.utils.DensityUtil;
import com.everyone.android.utils.LogUtil;

/**
 * 功能描述:新鲜事列表数据适配器
 * @author android_ls
 */
public class FreshNewsAdapter extends BaseAdapter {
    /**
     * LOG打印标签
     */
    private static final String TAG = "FreshNewsAdapter";

    private LayoutInflater inflater;

    private LinkedList<FreshNews> mFreshNewsList;

    private EveryoneActivity mActivity;

    private ImageLoader mImageLoader;

    public FreshNewsAdapter(EveryoneActivity activity, LinkedList<FreshNews> freshNewsList) {
        inflater = LayoutInflater.from(activity);
        mActivity = activity;
        mFreshNewsList = freshNewsList;
        this.mImageLoader = new ImageLoader(mActivity);
    }

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

    @Override
    public Object getItem(int arg0) {
        return mFreshNewsList.get(arg0);
    }

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

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.fresh_news_list_item, null);
            holder = new ViewHolder();
            holder.imageView1 = (ImageView) convertView.findViewById(R.id.iv_user_image);
            holder.text1 = (TextView) convertView.findViewById(R.id.tv_nickname);

            holder.text2 = (TextView) convertView.findViewById(R.id.tv_content);
            holder.imageView2 = (ImageView) convertView.findViewById(R.id.iv_content_picture);

            holder.linearLayout1 = (LinearLayout) convertView.findViewById(R.id.ll_comments_content);
            holder.linearLayout2 = (LinearLayout) convertView.findViewById(R.id.ll_update_status);

            holder.text3 = (TextView) convertView.findViewById(R.id.tv_published);
            holder.text4 = (TextView) convertView.findViewById(R.id.tv_source);

            holder.text5 = (TextView) convertView.findViewById(R.id.tv_status_name);
            holder.text6 = (TextView) convertView.findViewById(R.id.tv_status_content);

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

        final FreshNews freshNews = mFreshNewsList.get(position);

        // 姓名
        holder.text1.setText(freshNews.getName());

        // 加载图像
        String headurl = freshNews.getHeadurl();
        LogUtil.i(TAG, "headurl = " + headurl);
        if (!TextUtils.isEmpty(headurl)) {
            int widthPx = DensityUtil.dip2px(mActivity, 43);
            ImageInfo imgInfo = new ImageInfo(holder.imageView1, headurl, widthPx, widthPx);
            mImageLoader.displayImage(imgInfo);
        }

        /* 下面这几个字段比较难区分,人人的官方文档里描述的不是很清楚,
         * 比如新鲜事内容的前缀在那种新鲜事类型下显示等。
         * 我的做法是与人人官方的应用对比,猜测在某种类型下,可能取得是下面的某个字段的值。
         * 猜的话,很容易搞错。
         */
        String description = freshNews.getDescription();
        LogUtil.i(TAG, "description = " + description);
        LogUtil.i(TAG, "freshNews.getMessage() = " + freshNews.getMessage());
        LogUtil.i(TAG, "freshNews.getTitle() = " + freshNews.getTitle());
        LogUtil.i(TAG, "freshNews.getPrefix() = " + freshNews.getPrefix());

        // 用户自定义输入内容,状态 
        String message = freshNews.getMessage();
        if (!TextUtils.isEmpty(message)) {
            holder.text2.setVisibility(View.VISIBLE);
            holder.text2.setText(message);
        } else {
            holder.text2.setVisibility(View.GONE);
        }

        // page代表公共主页新鲜事
        int feedType = freshNews.getFeed_type();
        switch (feedType) {
        case 10: // 更新状态的新鲜事。 
        case 11: // page更新状态的新鲜事。 

            // 设置状态标识图标
            holder.text3.setCompoundDrawablesWithIntrinsicBounds(R.drawable.v5_0_1_newsfeed_status_icon, 0, 0, 0);

            // 内容的前缀
            String prefix = freshNews.getPrefix();
            if (!TextUtils.isEmpty(prefix)) {
                holder.text2.setVisibility(View.VISIBLE);
                holder.text2.setText(prefix);
            } else {
                holder.text2.setVisibility(View.GONE);
            }

            LinkedList<Attachment> attachment = freshNews.getAttachment();
            if (attachment != null) {
                int size = attachment.size();
                LogUtil.i(TAG, "size = " + size);
                if (size > 0) {
                    holder.linearLayout2.setVisibility(View.VISIBLE);
                    for (int i = 0; i < size; i++) {
                        // 这里测试只取第一个
                        Attachment att = attachment.get(i);
                        if ("status".equals(att.getMedia_type())) {
                            LogUtil.i(TAG, "att.getContent() = " + att.getContent());

                            holder.text5.setText(att.getOwner_name());
                            holder.text6.setText(att.getContent());
                            break;
                        }
                    }
                } else {
                    holder.linearLayout2.setVisibility(View.GONE);
                }
            } else {
                holder.linearLayout2.setVisibility(View.GONE);
            }

            break;
        case 20: // 发表日志的新鲜事。 
        case 22: // page发表日志的新鲜事。 

            break;
        case 21: // 分享日志的新鲜事。 
        case 23: // page分享日志的新鲜事。 

            break;
        case 30: // 上传照片的新鲜事。
        case 31: // page上传照片的新鲜事。  

            break;
        case 32: // 分享照片的新鲜事。 
        case 33: // 分享相册的新鲜事。  

            break;
        // ...
        default:
            break;
        }

        // 动态生成显示评论信息的Item
        Comments comments = freshNews.getComments();
        if (comments != null) {
            LinkedList<Comment> commentList = comments.getComment();
            if (commentList != null) {
                holder.linearLayout1.setVisibility(View.VISIBLE);

                if (holder.linearLayout1.getChildCount() > 0) {
                    holder.linearLayout1.removeAllViews();
                }

                int count = comments.getCount();
                if (count > 0) {
                    TextView tvCount = new TextView(mActivity);
                    tvCount.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
                    tvCount.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
                    tvCount.setSingleLine();
                    tvCount.setCompoundDrawablePadding(5);
                    tvCount.setPadding(0, 10, 0, 0);
                    tvCount.setText(count + "条评论");
                    tvCount.setTextColor(Color.parseColor("#ff005092"));
                    tvCount.setCompoundDrawablesWithIntrinsicBounds(R.drawable.fresh_news_comment_icon, 0, 0, 0);
                    holder.linearLayout1.addView(tvCount);
                }

                int size = commentList.size();
                LogUtil.i(TAG, "commentList size = " + size);
                for (int i = 0; i < size; i++) {
                    Comment comment = commentList.get(i);
                    LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

                    TextView tvContent = new TextView(mActivity);
                    tvContent.setLayoutParams(layoutParams);
                    tvContent.setTextColor(Color.BLACK);
                    tvContent.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
                    tvContent.setSingleLine();
                    tvContent.setPadding(0, 10, 0, 0);
                    tvContent.setText(comment.getName() + ":" + comment.getText());
                    holder.linearLayout1.addView(tvContent);

                    TextView tvTime = new TextView(mActivity);
                    tvTime.setTextColor(Color.GRAY);
                    tvTime.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
                    tvTime.setLayoutParams(layoutParams);
                    tvContent.setPadding(0, 5, 0, 10);
                    tvTime.setText(comment.getTime());
                    holder.linearLayout1.addView(tvTime);
                }

            } else {
                holder.linearLayout1.setVisibility(View.GONE);
            }
        } else {
            holder.linearLayout1.setVisibility(View.GONE);
        }

        // 对获取的时间字符串的处理
        String updateTime = freshNews.getUpdate_time();
        if (!TextUtils.isEmpty(updateTime)) {
            updateTime = updateTime.substring(updateTime.indexOf("-") + 1, updateTime.lastIndexOf(":"));
            updateTime = updateTime.replace("-", "月");
            updateTime = updateTime.replace(" ", "日 ");
            int index = updateTime.indexOf("0");
            if (index == 0) {
                updateTime = updateTime.substring(index + 1);
            }

            holder.text3.setText(updateTime);
        }

        // 来自那种客户端
        Source source = freshNews.getSource();
        if (source != null) {
            holder.text4.setText("来自:" + source.getText());
        }

        return convertView;
    }

    static class ViewHolder {

        public LinearLayout linearLayout1;

        public LinearLayout linearLayout2;

        public ImageView imageView1;

        public ImageView imageView2;

        public TextView text1;

        public TextView text2;

        public TextView text3;

        public TextView text4;

        public TextView text5;

        public TextView text6;
    }
}

     这篇就先聊到这里了,后面的待续。。。

             
 

 

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值