public class ImageBrowserActivity extends SwipeBackActivity {

    private ViewPager mViewPager;
    private List<String> imgUrls = new ArrayList<>();
    private int position;
    private ImagePagerAdapter adapter;
    private TextView tv_pic_num;
    private String picNum;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SwipeBackLayout mSwipeBackLayout = getSwipeBackLayout();
        mSwipeBackLayout.setEdgeTrackingEnabled(SwipeBackLayout.EDGE_LEFT);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mViewPager.removeOnPageChangeListener(onPageChangeListener);
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        if (imgUrls != null)
            outState.putStringArrayList("imgUrls", (ArrayList) imgUrls);
        outState.putInt("positon", position);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        if (savedInstanceState == null) {
            imgUrls = getIntent().getStringArrayListExtra("imgUrls");
            position = getIntent().getIntExtra("position", 0);
        } else {
            imgUrls = savedInstanceState.getStringArrayList("imgUrls");
            position = savedInstanceState.getInt("position");
        }
        adapter = new ImagePagerAdapter(this, imgUrls);
        mViewPager.setAdapter(adapter);
        mViewPager.setCurrentItem(position);
        picNum = getString(R.string.pic_num);
        mViewPager.addOnPageChangeListener(onPageChangeListener);
        tv_pic_num.setText(String.format(picNum, position + 1, imgUrls.size()));
    }

    ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            tv_pic_num.setText(String.format(picNum, position + 1, imgUrls.size()));
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };

    @Override
    protected void initToolBar() {
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_image_browser);
        mViewPager = (ViewPager) findViewById(R.id.mViewPager);
        tv_pic_num = (TextView) findViewById(R.id.tv_pic_num);
        ImageView iv_back = (ImageView) findViewById(R.id.iv_back);
        TextView tv_save = (TextView) findViewById(R.id.tv_save);
        iv_back.setOnClickListener(listener);
        tv_save.setOnClickListener(listener);
    }

    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.iv_back:
                    finish();
                    break;
                case R.id.tv_save:
                    String url = imgUrls.get(mViewPager.getCurrentItem());
                    if (url != null) {
                        if (SharePrefUtil.getBoolean(ImageBrowserActivity.this, "load_hd_pic", false)) {
                            url = url.replace("thumbnail", "large");
                        } else {
                            url = url.replace("thumbnail", "bmiddle");
                        }
                        adapter.savePicture(url);
                    }
                    break;
            }
        }
    };

    public static void actionStart(Context context, ArrayList imgUrls, int position) {
        Intent intent = new Intent(context, ImageBrowserActivity.class);
        intent.putStringArrayListExtra("imgUrls", imgUrls);
        intent.putExtra("position", position);
        context.startActivity(intent);
    }

} public class MainActivity extends BaseActivity implements RefreshWeiboTimelineReceiver.OnUpdateUIListener {

    private DrawerLayout mDrawerLayout; //抽屉
    private ActionBarDrawerToggle toggle; //在ActionBar上的抽屉按钮
    private Toolbar mToolbar;
    private TabLayout mTabLayout;
    private boolean isDrawerOpened = false; //判断DrawerLayout是否打开

    private FloatingActionButton mFloatingActionButton;
    private Handler handler = new Handler();
    private ViewPager mViewPager;

    private FragmentAdapter adapter;
    private FragmentManager fm;
    public static final int SEND_NEW_WEIBO = 1001;
    public static final int SEND_NEW_COMMENT = 1003;
    public static final int SEND_NEW_REPOST = 1005;
    private boolean isLastShown = false; //用于fabbutton上一个状态是否显示
    private long firstTime;
    private CoordinatorLayout mCoordinatorLayout;
    private RefreshWeiboTimelineReceiver receiver;
    private TextView tv_unread_remind;

    @Override
    protected void initData(Bundle savedInstanceState) {
        //检查token是否过期
        checkTokenExpireIn();
        //开启查询未读微博的service
        Intent intent = new Intent(MainActivity.this, CheckUnreadService.class);
        intent.setAction(CheckUnreadService.START_TIMER);
        startService(intent);
        //注册广播，用于监听屏幕开启，屏幕关闭，以及未读微博的更新提醒
        receiver = new RefreshWeiboTimelineReceiver();
        receiver.setOnUpdateUIListener(this);
        IntentFilter filter = new IntentFilter();
        filter.addAction(RefreshWeiboTimelineReceiver.INTENT_UNREAD_UPDATE); //更新未读
        filter.addAction(RefreshWeiboTimelineReceiver.INTENT_FAB_CHANGE); //改变fab
        filter.addAction(Intent.ACTION_SCREEN_OFF); //关闭屏幕
        filter.addAction(Intent.ACTION_USER_PRESENT); //解锁屏幕
        registerReceiver(receiver, filter);
    }

    @Override
    protected void onDestroy() {
        stopService(new Intent(MainActivity.this, CheckUnreadService.class));
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
        super.onDestroy();
    }

    //查询用户access_token的授权相关信息
    private void checkTokenExpireIn() {
        final String access_token = SharePrefUtil.getString(this, "access_token", "");
        if (access_token != "") {
            String url = AppConstant.GET_TOKEN_INFO_URL + "?access_token=" + access_token;
            JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject jsonObject) {
                    try {
                        String expire_in = jsonObject.getString("expire_in");
                        int second = Integer.parseInt(expire_in);
                        if (second > 0) {
                            SharePrefUtil.saveString(MainActivity.this, "expire_in", expire_in);
                        } else {
                            goToAuthorizeActivity();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }, errorListener) {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    Map<String, String> map = new HashMap<String, String>();
                    map.put("access_token", access_token);
                    return map;
                }
            };
            mQueue.add(jsonObjectRequest);
        } else {
            goToAuthorizeActivity();
        }
    }

    private void goToAuthorizeActivity() {
        AuthorizeActivity.actionStart(this);
        finish();
    }

    Response.ErrorListener errorListener = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            LogUtils.i(volleyError.toString());
        }
    };

    @Override
    protected void initToolBar() {
        mToolbar.setTitleTextColor(Color.WHITE);
        setSupportActionBar(mToolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);

        }
        toggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
            @Override
            public void onDrawerClosed(View drawerView) {
                if (isLastShown) {
                    mFloatingActionButton.show();
                }
                isDrawerOpened = false;
                super.onDrawerClosed(drawerView);
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                isDrawerOpened = true;
                isLastShown = mFloatingActionButton.isShown();
                mFloatingActionButton.hide();
                super.onDrawerOpened(drawerView);
            }
        };
        //把toggle和ActionBar同步状态
        mDrawerLayout.setDrawerListener(toggle);
        toggle.syncState();
    }


    @Override
    protected void initView() {
        setContentView(R.layout.activity_main);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.mDrawerLayout);
        mToolbar = (Toolbar) findViewById(R.id.mToolbar);
        mTabLayout = (TabLayout) findViewById(R.id.mTabLayout);
        if (mTabLayout != null) {
            setupTabLayoutContent(mTabLayout);
        }
        NavigationView mNavigationView = (NavigationView) findViewById(R.id.mNavigationView);
        mFloatingActionButton = (FloatingActionButton) findViewById(R.id.mFloatingActionButton);
        mViewPager = (ViewPager) findViewById(R.id.mViewPager);
        mCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.mCoordinatorLayout);
        tv_unread_remind = (TextView) findViewById(R.id.tv_unread_remind);
        if (adapter == null) {
            setupViewPagerContent();
        }
        if (mNavigationView != null) {
            setupDrawerContent(mNavigationView);
        }
        if (mFloatingActionButton != null) {
            setupFloatingActionButtonContent(mFloatingActionButton);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            case SEND_NEW_WEIBO:
                if (resultCode == PublishActivity.SEND_WEIBO_SUCCESS) {
                    LogUtils.i("send weibo success");
                    CommonUtil.showNotification(MainActivity.this, R.string.send_remind, R.string.send_success, R.drawable.ic_done_light, true);
                    final Fragment item = adapter.getItem(0);
                    View rootView = item.getView();
                    CommonUtil.showSnackbar(rootView, R.string.publish_success, getResources().getColor(R.color.Indigo_colorPrimary), Snackbar.LENGTH_LONG, R.string.click_to_refresh, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mViewPager.setCurrentItem(0, true);
                            ((WeiboTimeLineFragment) item).refreshWeibo();
                        }
                    });
                }
                break;
            case SEND_NEW_COMMENT:
                if (resultCode == PublishActivity.SEND_COMMENT_SUCCESS) {
                    LogUtils.i("send comment success");
                    CommonUtil.showNotification(MainActivity.this, R.string.send_remind, R.string.send_success, R.drawable.ic_done_light, true);
                }
                break;
            case SEND_NEW_REPOST:
                if (resultCode == PublishActivity.SEND_REPOST_SUCCESS) {
                    LogUtils.i("send repost success");
                    CommonUtil.showNotification(MainActivity.this, R.string.send_remind, R.string.send_success, R.drawable.ic_done_light, true);
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void setupTabLayoutContent(TabLayout mTabLayout) {
        mTabLayout.setSelectedTabIndicatorColor(getResources().getColor(android.R.color.white));
        mTabLayout.setSelectedTabIndicatorHeight(CommonUtil.dip2px(this, 2));
        mTabLayout.setTabTextColors(getResources().getColor(R.color.unselected_text_color), getResources().getColor(android.R.color.white));
    }

    private void setupFloatingActionButtonContent(FloatingActionButton mFloatingActionButton) {
        //Fab功能
        final int flag = SharePrefUtil.getInt(this, "fab_function", 0);
        if (0 == flag) {
            mFloatingActionButton.setImageResource(R.drawable.ic_create_light);
        } else {
            mFloatingActionButton.setImageResource(R.drawable.ic_refresh_light);
        }
        // Fab位置
        final int position = SharePrefUtil.getInt(this, "fab_position", 1);
        CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) mFloatingActionButton.getLayoutParams();
        if (1 == position) {
            layoutParams.anchorGravity = Gravity.END | Gravity.BOTTOM | Gravity.RIGHT;
        } else {
            layoutParams.anchorGravity = Gravity.START | Gravity.BOTTOM | Gravity.LEFT;
        }
        mFloatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (0 == flag) {
                    // 得到状态栏的高度
                    DisplayMetrics dm = new DisplayMetrics();
                    getWindowManager().getDefaultDisplay().getMetrics(dm);
                    int topOffset = dm.heightPixels - mCoordinatorLayout.getMeasuredHeight();

                    int[] startingLocation = new int[2];
                    view.getLocationOnScreen(startingLocation);
                    startingLocation[0] += view.getWidth() / 2;
                    startingLocation[1] = startingLocation[1] - topOffset + view.getHeight() / 2;
                    Intent intent = new Intent(MainActivity.this, PublishActivity.class);
                    intent.putExtra("type", PublishActivity.SEND_WEIBO);
                    intent.putExtra("isFromFAButton", true);
                    intent.putExtra(PublishActivity.ARG_REVEAL_START_LOCATION, startingLocation);
                    startActivityForResult(intent, SEND_NEW_WEIBO);
                    overridePendingTransition(0, 0);
                } else {
                    Fragment frag = adapter.getItem(mViewPager.getCurrentItem());
                    ((WeiboTimeLineFragment) frag).refreshWeibo();
                }
            }
        });
    }

    //设置ViewPager内容
    private void setupViewPagerContent() {
        fm = getSupportFragmentManager();
        adapter = new FragmentAdapter(fm);
        adapter.addFragment(FragmentFactory.newInstance(AppConstant.HOME_TIMELINE_URL), getResources().getString(R.string.all_weibo));
        adapter.addFragment(FragmentFactory.newInstance(AppConstant.STATUSES_BILATERAL_TIMELINE_URL), getResources().getString(R.string.bilateral_weibo));
        mViewPager.setAdapter(adapter);
        mTabLayout.setupWithViewPager(mViewPager);
    }

    //设置navigationView内容
    private void setupDrawerContent(NavigationView navigationView) {

        navigationView.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(MenuItem menuItem) {
                        LogUtils.i(menuItem.getItemId() + "");
                        menuItem.setCheckable(false);
                        switch (menuItem.getItemId()) {
                            case R.id.nav_search:
                                SearchUserActivity.actionStart(MainActivity.this, SearchUserActivity.SEARCH_USER);
                                break;
                            case R.id.nav_nearly:
                                NearlyDynamicActivity.actionStart(MainActivity.this);
                                break;
                            case R.id.nav_hot:
                                PublicWeiboActivity.actionStart(MainActivity.this);
                                break;
                            case R.id.nav_favorite:
                                MyFavoriteActivity.actionStart(MainActivity.this);
                                break;
                            case R.id.nav_draft:
                                DraftActivity.actionStart(MainActivity.this);
                                break;
                        }
                        return true;
                    }
                });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_remind:
                RemindActivity.actionStart(MainActivity.this);
                break;
            case R.id.action_send_weibo:
                Intent intent = new Intent();
                intent.setClass(this, PublishActivity.class);
                intent.putExtra("type", PublishActivity.SEND_WEIBO);
                startActivity(intent);
                break;
            case R.id.action_settings:
                SettingsActivity.actionStart(MainActivity.this);
                break;
            case R.id.action_about:
                AboutActivity.actionStart(MainActivity.this);
                break;
            case R.id.action_exit:
                finish();
                removeAllActivities();
                break;

        }
        return toggle.onOptionsItemSelected(item) | super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isDrawerOpened) {
                mDrawerLayout.closeDrawers();
                isDrawerOpened = false;
            } else {
                long secondTime = System.currentTimeMillis();
                if (secondTime - firstTime > 2000) {
                    CommonUtil.showSnackbar(mViewPager.getChildAt(mViewPager.getCurrentItem()), R.string.again_to_exit, getResources().getColor(R.color.Indigo_colorPrimary));
                    firstTime = secondTime;
                } else {
                    finish();
                    removeAllActivities();
                }
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    public void updateUI(int unreadCount) {
        String title = String.format(getString(R.string.unread_weibo), unreadCount);
        tv_unread_remind.setText(title);
    }

    @Override
    public void updateFab() {
        setupFloatingActionButtonContent(mFloatingActionButton);
    }
} public class MyFavoriteActivity extends SwipeBackActivity {

    private SwipeBackLayout mSwipeBackLayout;
    private Toolbar mToolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSwipeBackLayout = getSwipeBackLayout();
        mSwipeBackLayout.setEdgeTrackingEnabled(SwipeBackLayout.EDGE_LEFT);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {

    }

    @Override
    protected void initToolBar() {
        mToolbar.setTitleTextColor(Color.WHITE);
        mToolbar.setTitle(R.string.my_favorite);
        setSupportActionBar(mToolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_my_favorite);
        mToolbar = (Toolbar) findViewById(R.id.mToolbar);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            case MainActivity.SEND_NEW_COMMENT:
                if (resultCode == PublishActivity.SEND_COMMENT_SUCCESS) {
                    CommonUtil.showNotification(MyFavoriteActivity.this, R.string.send_remind, R.string.send_success, R.drawable.ic_done_light, true);
                }
                break;
            case MainActivity.SEND_NEW_REPOST:
                if (resultCode == PublishActivity.SEND_REPOST_SUCCESS) {
                    CommonUtil.showNotification(MyFavoriteActivity.this, R.string.send_remind, R.string.send_success, R.drawable.ic_done_light, true);
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public static void actionStart(Context context) {
        Intent intent = new Intent(context, MyFavoriteActivity.class);
        context.startActivity(intent);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

} public class NearlyDynamicActivity extends SwipeBackActivity {

    private SwipeBackLayout mSwipeBackLayout;
    private Toolbar mToolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSwipeBackLayout = getSwipeBackLayout();
        mSwipeBackLayout.setEdgeTrackingEnabled(SwipeBackLayout.EDGE_LEFT);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {

    }

    @Override
    protected void initToolBar() {
        mToolbar.setTitleTextColor(Color.WHITE);
        mToolbar.setTitle(R.string.nearly_dynamic);
        setSupportActionBar(mToolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_nearly_dynamic);
        mToolbar = (Toolbar) findViewById(R.id.mToolbar);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            case MainActivity.SEND_NEW_COMMENT:
                if (resultCode == PublishActivity.SEND_COMMENT_SUCCESS) {
                    CommonUtil.showNotification(NearlyDynamicActivity.this, R.string.send_remind, R.string.send_success, R.drawable.ic_done_light, true);
                }
                break;
            case MainActivity.SEND_NEW_REPOST:
                if (resultCode == PublishActivity.SEND_REPOST_SUCCESS) {
                    CommonUtil.showNotification(NearlyDynamicActivity.this, R.string.send_remind, R.string.send_success, R.drawable.ic_done_light, true);
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public static void actionStart(Context context) {
        Intent intent = new Intent(context, NearlyDynamicActivity.class);
        context.startActivity(intent);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

} public class PublishActivity extends BaseActivity implements RevealBackgroundView.OnStateChangeListener {

    private Toolbar mToolbar;
    private ActionBar actionBar;
    private ImageButton ib_location;
    private ImageButton ib_photo;
    private ImageButton ib_emotion;
    private ImageButton ib_noti;
    private ImageButton ib_sharp;
    private ImageButton ib_send;
    private ImageView iv_add;
    private TextView tv_location;
    private EditText et_content;
    private CheckBox cb_comment_to_auth;
    private TextView tv_word_num;
    private LinearLayout ll_images;
    private HorizontalScrollView mHorizontalScrollView;
    private Map<DeleteImageView, String> imageMap = new HashMap<>();
    private List<String> strList = new ArrayList<>();
    private LoadImageAsyncTask loadImageAsyncTask;
    private GridView gv_emotion;
    private EmotionAdapter adapter;
    private RevealBackgroundView vRevealBackground;

    public static final int SEND_WEIBO = 1010; //发布微博
    public static final int SEND_COMMENT = 1020; //发布评论
    public static final int SEND_REPOST = 1030; //转发微博
    public static final int REFRESH_DRAFT = 1040; //刷新草稿箱
    public static final int REPLY_COMMENT = 1050; //回复评论

    public static final String ARG_REVEAL_START_LOCATION = "reveal_start_location";

    private static final int TAKE_PHOTO = 1002; //相机拍照
    private static final int TAKE_GALLERY = 1003; //系统图库

    private boolean isPicture = false; //是否发含有图片的微博
    private boolean isLocation = false; //是否定位
    private double longitude; //经度
    private double latitude; //维度
    private int type; //源Activity 类型
    private String url; //网络url
    private String idstr; //微博ID

    public static final int SEND_WEIBO_SUCCESS = 1200; //发微博成功
    public static final int SEND_COMMENT_SUCCESS = 1250; //评论成功
    public static final int SEND_REPOST_SUCCESS = 1300; //转发成功

    private LinearLayout mLinearLayout;
    private boolean isFromFAButton; //是否从含有FloatingActionButton的界面跳转过来
    private int draft_id; //草稿箱ID
    private String cid; // 回复某人评论时的评论ID

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (type == PublishActivity.SEND_WEIBO && isFromFAButton) {
            setupRevealBackground(savedInstanceState);
        } else {
            mLinearLayout.setBackgroundColor(getResources().getColor(R.color.activity_bg_color));
            vRevealBackground.setVisibility(View.GONE);
        }
    }

    private void setupRevealBackground(Bundle savedInstanceState) {
        vRevealBackground.setFillPaintColor(getResources().getColor(R.color.Indigo_colorPrimary));
        vRevealBackground.setOnStateChangeListener(this);
        if (savedInstanceState == null) {
            final int[] startingLocation = getIntent().getIntArrayExtra(ARG_REVEAL_START_LOCATION);
            vRevealBackground.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
                @Override
                public boolean onPreDraw() {
                    vRevealBackground.getViewTreeObserver().removeOnPreDrawListener(this);
                    vRevealBackground.startFromLocation(startingLocation);
                    return false;
                }
            });
        } else {
            vRevealBackground.setToFinishedFrame();
        }
    }

    @Override
    public void onStateChange(int state) {
        if (RevealBackgroundView.STATE_FINISHED == state) {
            if (RevealBackgroundView.STATE_FINISHED == state) {
                vRevealBackground.setVisibility(View.GONE);
                mLinearLayout.setBackgroundColor(getResources().getColor(R.color.activity_bg_color));
            }
        }
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        Intent intent = getIntent();
        draft_id = intent.getIntExtra("draft_id", 0);
        type = intent.getIntExtra("type", 0);
        isFromFAButton = intent.getBooleanExtra("isFromFAButton", false);
        idstr = intent.getStringExtra("idstr");
        cid = intent.getStringExtra("cid");
        String text = intent.getStringExtra("text");
        if (text != null) {
            et_content.setText(text);
        }
        switch (type) {
            case SEND_WEIBO:   //发微博
                actionBar.setTitle(R.string.publish_weibo);
                url = AppConstant.STATUSES_UPDATE_URL;
                break;
            case SEND_COMMENT:  //评论
                boolean isReweeted = intent.getBooleanExtra("isReweeted", false);
                actionBar.setTitle(R.string.comment_weibo);
                ib_location.setVisibility(View.GONE);
                ib_photo.setVisibility(View.GONE);
                et_content.setHint(R.string.comment_weibo);
                if (isReweeted) {
                    cb_comment_to_auth.setVisibility(View.VISIBLE);
                    cb_comment_to_auth.setText(R.string.comment_to_original_weibo);
                }
                url = AppConstant.COMMENTS_CREATE_URL;
                break;
            case SEND_REPOST:  //转发
                actionBar.setTitle(R.string.repost_weibo);
                ib_location.setVisibility(View.GONE);
                ib_photo.setVisibility(View.GONE);
                ib_sharp.setVisibility(View.GONE);
                cb_comment_to_auth.setVisibility(View.VISIBLE);
                et_content.setHint(R.string.repost_weibo);
                et_content.setSelection(0);
                url = AppConstant.STATUSES_REPOST_URL;
                break;
            case REPLY_COMMENT:
                actionBar.setTitle(R.string.reply_comment);
                ib_location.setVisibility(View.GONE);
                ib_photo.setVisibility(View.GONE);
                cb_comment_to_auth.setVisibility(View.VISIBLE);
                et_content.setHint(R.string.reply_comment);
                url = AppConstant.COMMENTS_REPLY_URL;
                break;
            default:
                break;
        }

    }

    @Override
    protected void initToolBar() {
        mToolbar.setTitleTextColor(Color.WHITE);
        setSupportActionBar(mToolbar);
        actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_publish);
        mToolbar = (Toolbar) findViewById(R.id.mToolbar);
        mHorizontalScrollView = (HorizontalScrollView) findViewById(R.id.mHorizontalScrollView);
        iv_add = (ImageView) findViewById(R.id.iv_add);
        et_content = (EditText) findViewById(R.id.et_content);
        ll_images = (LinearLayout) findViewById(R.id.ll_images);
        ib_location = (ImageButton) findViewById(R.id.ib_location);
        ib_photo = (ImageButton) findViewById(R.id.ib_photo);
        ib_emotion = (ImageButton) findViewById(R.id.ib_emotion);
        ib_noti = (ImageButton) findViewById(R.id.ib_noti);
        ib_sharp = (ImageButton) findViewById(R.id.ib_sharp);
        ib_send = (ImageButton) findViewById(R.id.ib_send);
        tv_location = (TextView) findViewById(R.id.tv_location);
        tv_word_num = (TextView) findViewById(R.id.tv_word_num);
        gv_emotion = (GridView) findViewById(R.id.gv_emotion);
        cb_comment_to_auth = (CheckBox) findViewById(R.id.cb_comment_to_auth);
        vRevealBackground = (RevealBackgroundView) findViewById(R.id.vRevealBackground);
        mLinearLayout = (LinearLayout) findViewById(R.id.mLinearLayout);

        adapter = new EmotionAdapter(this, new ArrayList<Emotion>());
        gv_emotion.setAdapter(adapter);
        gv_emotion.setOnItemClickListener(onItemClickListener);
        et_content.addTextChangedListener(watcher);
        et_content.setOnClickListener(listener);
        ib_location.setOnClickListener(listener);
        ib_photo.setOnClickListener(listener);
        ib_emotion.setOnClickListener(listener);
        ib_noti.setOnClickListener(listener);
        ib_sharp.setOnClickListener(listener);
        ib_send.setOnClickListener(listener);
        iv_add.setOnClickListener(listener);
    }

    TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            String content = s.toString();
            String num = tv_word_num.getText().toString();
            tv_word_num.setText(content.length() + num.substring(num.indexOf("/"), num.length()));
        }
    };

    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.ib_location:
                    processLocation();
                    break;
                case R.id.ib_photo:
                    processPhoto(v);
                    break;
                case R.id.ib_emotion:
                    processEmotion();
                    break;
                case R.id.ib_noti:
                    processNoti();
                    break;
                case R.id.ib_sharp:
                    processTopic();
                    break;
                case R.id.iv_add:
                    processPhoto(v);
                    break;
                case R.id.ib_send:
                    processSendWeibo(v);
                    break;
                case R.id.et_content:
                    if (gv_emotion.isShown()) {
                        gv_emotion.setVisibility(View.GONE);
                    }
                    break;
            }
        }
    };

    AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Emotion emotion = adapter.getList().get(position);
            Bitmap bitmap = BitmapFactory.decodeByteArray(emotion.getData(), 0, emotion.getData().length);
            if (bitmap != null) {
                SpannableString ss = new SpannableString(emotion.getKey());
                ImageSpan imageSpan = new ImageSpan(PublishActivity.this, bitmap, ImageSpan.ALIGN_BOTTOM);
                ss.setSpan(imageSpan, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                et_content.getText().insert(et_content.getSelectionEnd(), ss);
            }
        }
    };

    // 处理 @ 事件
    private void processNoti() {
        Intent intent = new Intent(this, SearchUserActivity.class);
        intent.putExtra("type", SearchUserActivity.AT_USER);
        startActivityForResult(intent, SearchUserActivity.AT_USER);
    }

    //选择表情
    private void processEmotion() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            imm.hideSoftInputFromWindow(PublishActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
        if (gv_emotion.isShown()) {
            gv_emotion.postDelayed(new Runnable() {
                @Override
                public void run() {
                    gv_emotion.setVisibility(View.GONE);
                }
            }, 300);
        } else {
            gv_emotion.setVisibility(View.VISIBLE);
        }
    }

    // 发布微博
    private void processSendWeibo(View v) {
        if (gv_emotion.isShown()) {
            gv_emotion.setVisibility(View.GONE);
        }
        final String content = et_content.getText().toString();
        if (TextUtils.isEmpty(content.trim()) && type != SEND_REPOST) {
            CommonUtil.showSnackbar(v, R.string.content_cannot_be_empty, getResources().getColor(R.color.Indigo_colorPrimary));
            return;
        }
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, sendWeiboListener, errorListener) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap();
                map.put("access_token", SharePrefUtil.getString(PublishActivity.this, "access_token", ""));
                map.put("status", content);
                switch (type) {
                    case SEND_WEIBO:
                        map.put("status", content);
                        if (isLocation) {
                            map.put("lat", String.valueOf(latitude));
                            map.put("long", String.valueOf(longitude));
                        }
                        break;
                    case SEND_COMMENT:
                        map.put("comment", content);
                        map.put("id", idstr);
                        if (cb_comment_to_auth.isChecked()) {
                            map.put("comment_ori", "1");
                        }
                        break;
                    case SEND_REPOST:
                        map.put("status", content);
                        map.put("id", idstr);
                        if (cb_comment_to_auth.isChecked()) {
                            map.put("is_comment", "1");
                        }
                        break;
                    case REPLY_COMMENT:
                        map.put("comment", content);
                        map.put("cid", cid);
                        map.put("id", idstr);
                        if (cb_comment_to_auth.isChecked()) {
                            map.put("comment_ori", "1");
                        }
                }
                return map;
            }
        };
        mQueue.add(stringRequest);
    }

    Response.Listener<String> sendWeiboListener = new Response.Listener<String>() {
        @Override
        public void onResponse(String s) {
            try {
                JSONObject jsonObject = new JSONObject(s);
                String idstr = jsonObject.getString("idstr");
                if (!TextUtils.isEmpty(idstr)) {
                    if (type == SEND_WEIBO) {
                        setResult(SEND_WEIBO_SUCCESS);
                    } else if (type == SEND_COMMENT) {
                        setResult(SEND_COMMENT_SUCCESS);
                    } else if (type == SEND_REPOST) {
                        setResult(SEND_REPOST_SUCCESS);
                    }
                    finish();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    // 处理点击 位置 事件
    private void processLocation() {
        Location location = CommonUtil.getLocation(PublishActivity.this);
        if (!isLocation) {
            if (location == null) {
                tv_location.setVisibility(View.VISIBLE);
                tv_location.setText(R.string.unknown_address);
            } else {
                latitude = location.getLatitude();
                longitude = location.getLongitude();
                isLocation = true;
                LogUtils.i("GPS坐标  longitude :" + longitude + ", latitude :" + latitude);
                String url = AppConstant.GEO_TO_ADDRESS_URL + "?access_token=" + SharePrefUtil.getString(PublishActivity.this, "access_token", "") + "&coordinate=" + longitude + "," + latitude;
                LogUtils.i("根据地理信息坐标返回实际地址 :" + url);
                getJsonData(url, jsonlistener, errorListener);
            }
        } else {
            tv_location.setVisibility(View.GONE);
            isLocation = false;
        }
    }

    Response.Listener<JSONObject> jsonlistener = new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject json) {
            try {
                JSONArray geo = json.getJSONArray("geos");
                JSONObject geo0 = geo.getJSONObject(0);
                String address = geo0.getString("address");
                LogUtils.i("实际地址 :" + address);
                tv_location.setVisibility(View.VISIBLE);
                tv_location.setText(address);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    Response.ErrorListener errorListener = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            CommonUtil.showToast(PublishActivity.this, "Network Error");
        }
    };

    private String imageUrl;

    // 处理点击 图片 事件
    private void processPhoto(View v) {
        if (imageMap.size() > 8) {
            Snackbar.make(v, R.string.no_more_pictures, Snackbar.LENGTH_SHORT).show();
            return;
        }
        CommonUtil.createItemAlertDialog(PublishActivity.this, getResources().getStringArray(R.array.photo_items), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent;
                switch (which) {
                    case 0:
                        File DatalDir = Environment.getExternalStorageDirectory();
                        File myDir = new File(DatalDir, "/DCIM/Camera");
                        myDir.mkdirs();
                        String mDirectoryname = DatalDir.toString() + "/DCIM/Camera";
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_hhmmss", Locale.SIMPLIFIED_CHINESE);
                        File tempfile = new File(mDirectoryname, "IMG_" + sdf.format(new Date()) + ".jpg");//tempfile为图片的路径
                        if (tempfile.isFile())
                            tempfile.delete();
                        intent = new Intent("android.media.action.IMAGE_CAPTURE");
                        imageUrl = tempfile.getAbsolutePath();
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUrl);
                        startActivityForResult(intent, TAKE_PHOTO);
                        break;
                    case 1:
                        String url = CommonUtil.getLatestCameraPicture(PublishActivity.this);
                        loadImageAsyncTask = new LoadImageAsyncTask();
                        loadImageAsyncTask.execute(url);
                        break;
                    case 2:
//                        intent = new Intent(Intent.ACTION_PICK,
//                                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);//调用android的图库
//                        startActivityForResult(intent, TAKE_GALLERY);
                        startActivityForResult(new Intent(PublishActivity.this, GridImageActivity.class), TAKE_GALLERY);
                        break;
                }
            }
        },true);
    }

    // 处理点击 # 事件
    private void processTopic() {
        et_content.getText().append("##");
        et_content.setSelection(et_content.getText().length() - 1);
    }

    class LoadImageAsyncTask extends AsyncTask<String, Void, Bitmap> {

        private DeleteImageView mDeleteImageView;
        private String url;
        private int imageWidth;
        private int imageHeight;
        private View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ll_images.removeView(mDeleteImageView);
                if (imageMap.containsKey(mDeleteImageView)) {
                    imageMap.remove(mDeleteImageView);
                }
                if(imageMap.size() == 0){
                    mHorizontalScrollView.setVisibility(View.GONE);
                }
            }
        };

        @Override
        protected Bitmap doInBackground(String... params) {
            // TODO 优化图片
            url = params[0];
            Bitmap bitmap = BitmapUtil.decodeSampledBitmapFromUrl(url, imageWidth, imageHeight);
            return bitmap;
        }


        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (bitmap != null) {
                mDeleteImageView.setImageBitmap(bitmap);
                mDeleteImageView.setOnDeleteClickListener(listener);
                imageMap.put(mDeleteImageView, url);
                strList.add(url);
            }
            if (imageMap.size() > 8) {
                iv_add.setVisibility(View.GONE);
            }
            LogUtils.i("image_url :" + url + ", imageMap_size :" + imageMap.size());
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if (mHorizontalScrollView.getVisibility() != View.VISIBLE) {
                mHorizontalScrollView.setVisibility(View.VISIBLE);
            }
            mDeleteImageView = new DeleteImageView(PublishActivity.this);
            mDeleteImageView.setBackgroundResource(R.drawable.bg_unselected_card_item_light);
            ll_images.addView(mDeleteImageView, ll_images.getChildCount() - 1);
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mDeleteImageView.getLayoutParams();
            layoutParams.width = CommonUtil.dip2px(PublishActivity.this, 90);
            layoutParams.height = CommonUtil.dip2px(PublishActivity.this, 90);
            layoutParams.setMargins(CommonUtil.dip2px(PublishActivity.this, 10), 0, CommonUtil.dip2px(PublishActivity.this, 10), 0);
            imageWidth = layoutParams.width;
            imageHeight = layoutParams.height;
            LogUtils.i("imageView" + (ll_images.getChildCount() - 1) + "width :" + imageWidth + " , height :" + imageHeight);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case TAKE_PHOTO:
                if (resultCode == RESULT_OK) {
                    Uri uri = data.getData();
                    if (uri == null) {
                        if (imageUrl != null) {
                            Bitmap bitmap = data.getParcelableExtra("data");
                            try {
                                OutputStream out = new FileOutputStream(imageUrl);
                                bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
                                out.flush();
                                out.close();
                                loadImageAsyncTask = new LoadImageAsyncTask();
                                loadImageAsyncTask.execute(imageUrl);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    } else {
                        String path = uri.getPath();
                        loadImageAsyncTask = new LoadImageAsyncTask();
                        loadImageAsyncTask.execute(path);
                    }
                }
                break;
            case TAKE_GALLERY:
                if (resultCode == RESULT_OK) {
//                    Uri uri = data.getData();
                    List<String> urls = data.getStringArrayListExtra("urls");
//                    Cursor cursor = getContentResolver().query(uri, null,
//                            null, null, null);
//                    cursor.moveToFirst();
//                    String imgPath = cursor.getString(1); // 图片文件路径
                    for (int i = 0; i < urls.size(); i++) {
                        LoadImageAsyncTask loadImageAsyncTask = new LoadImageAsyncTask();
                        loadImageAsyncTask.execute(urls.get(i));
                    }

                }
                break;
            case SearchUserActivity.AT_USER:
                if (resultCode == RESULT_OK) {
                    String screen_name = data.getStringExtra("screen_name");
                    et_content.getText().insert(et_content.getSelectionEnd(), "@" + screen_name + " ");
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                saveToDraft();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            saveToDraft();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /*
     *返回提示是否保存到草稿箱
     */
    private void saveToDraft() {
        //如果表情框出现，则隐藏
        if (gv_emotion.isShown()) {
            gv_emotion.setVisibility(View.GONE);
            return;
        }
        // 如果是回复评论，直接finish
        if (type == REPLY_COMMENT) {
            finish();
            return;
        }
        final String content = et_content.getText().toString();
        if (!TextUtils.isEmpty(content)) {
            CommonUtil.createMessageAlertDialog(this, getResources().getString(R.string.tip), getResources().getString(R.string.save_draft), getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            }, getResources().getString(R.string.confirm), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    MyApplication.getExecutor().execute(
                            new Runnable() {
                                @Override
                                public void run() {
                                    if (draft_id == 0) {
                                        Draft d = new Draft(0, type, content, strList, idstr);
                                        DraftDB.addDraft(d);
                                    } else {
                                        Draft d = new Draft(draft_id, type, content, strList, idstr);
                                        DraftDB.updateDraft(d);
                                    }
                                }
                            });
                    if (draft_id != 0) {
                        setResult(REFRESH_DRAFT);
                    }
                    finish();
                }
            }, true);
        } else {
            finish();
        }

    }

} public class UserDetailsActivity extends SwipeBackActivity {

    private Toolbar mToolbar;
    private ViewPager mViewPager;
    private ImageView iv_cover;
    private CircleImageView civ_avatar;
    private TextView tv_screen_name;
    private TextView tv_location;
    private TextView tv_follower_num;
    private TextView tv_follow_num;
    private TextView tv_weibo_num;
    private TextView tv_verified_reason;
    private TextView tv_description;
    private FragmentManager fragmentManager;
    private FragmentAdapter adapter;
    private ImageLoader imageLoader = ImageLoader.getInstance();
    private DisplayImageOptions options = new DisplayImageOptions.Builder()
            .cacheInMemory(true)
            .cacheOnDisk(true)
            .bitmapConfig(Bitmap.Config.RGB_565)
            .build();
    private TabLayout mTabLayout;
    private String screen_name;
    private SwipeBackLayout mSwipeBackLayout;
    private User user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSwipeBackLayout = getSwipeBackLayout();
        mSwipeBackLayout.setEdgeTrackingEnabled(SwipeBackLayout.EDGE_LEFT);
    }


    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        outState.putString("screen_name", screen_name);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        if (savedInstanceState == null) {
            screen_name = getIntent().getStringExtra("screen_name");
        } else {
            screen_name = savedInstanceState.getString("screen_name");
        }
        if (TextUtils.isEmpty(screen_name)) {
            return;
        }
        String url = AppConstant.USERS_SHOW_URL + "?access_token=" +
                SharePrefUtil.getString(this, "access_token", "") + "&screen_name=" + screen_name;
        LogUtils.i("用户信息url ：" + url);
        getData(url, listener, errorListener);
    }

    Response.Listener<String> listener = new Response.Listener<String>() {
        @Override
        public void onResponse(String result) {
            user = JsonUtils.getBeanFromJson(result, User.class);
            initHeaderViewData();
            initMenu();
            setupViewPagerContent();
        }
    };

    Response.ErrorListener errorListener = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {

        }
    };

    private void initHeaderViewData() {
        if (user != null) {
            imageLoader.displayImage(user.getAvatar_large(), civ_avatar, options);
            imageLoader.displayImage(user.getCover_image_phone(), iv_cover, options);
            tv_screen_name.setText(user.getScreen_name());
            Drawable drawable = null;
            if ("m".equals(user.getGender())) {
                drawable = getResources().getDrawable(R.drawable.male);
            } else if ("f".equals(user.getGender())) {
                drawable = getResources().getDrawable(R.drawable.female);
            }
            if (drawable != null) {
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                tv_screen_name.setCompoundDrawables(null, null, drawable, null);
                tv_screen_name.setCompoundDrawablePadding(CommonUtil.dip2px(this, 5));
            }
            tv_location.setText(user.getLocation());
            tv_follower_num.setText(getResources().getString(R.string.follower) + CommonUtil.getNumString(user.getFollowers_count()));
            tv_follow_num.setText(getResources().getString(R.string.follow) + CommonUtil.getNumString(user.getFriends_count()));
            tv_weibo_num.setText(getResources().getString(R.string.weibo) + CommonUtil.getNumString(user.getStatuses_count()));
            if (user.isVerified()) {
                tv_verified_reason.setText(user.getVerified_reason());
            } else {
                tv_verified_reason.setVisibility(View.GONE);
            }
            tv_description.setText(user.getDescription());
        }
    }

    @Override
    protected void initToolBar() {
        mToolbar.setTitle("");
        mToolbar.setTitleTextColor(Color.WHITE);
        setSupportActionBar(mToolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_user_details);
        mToolbar = (Toolbar) findViewById(R.id.mToolbar);
        mViewPager = (ViewPager) findViewById(R.id.mViewPager);
        mTabLayout = (TabLayout) findViewById(R.id.mTabLayout);
        setupTabLayoutContent(mTabLayout);
        initHeaderView();
    }

    private void setupTabLayoutContent(TabLayout mTabLayout) {
        mTabLayout.setSelectedTabIndicatorColor(getResources().getColor(R.color.Indigo_colorPrimary));
        mTabLayout.setSelectedTabIndicatorHeight(CommonUtil.dip2px(this, 2));
        mTabLayout.setTabTextColors(getResources().getColor(R.color.unselected_text_color), getResources().getColor(R.color.Indigo_colorPrimary));
    }

    //设置ViewPager内容
    private void setupViewPagerContent() {
        fragmentManager = getSupportFragmentManager();
        adapter = new FragmentAdapter(fragmentManager);
        adapter.addFragment(FragmentFactory.getDetailsFragment(user.getIdstr(), 0), getResources().getString(R.string.all));
        adapter.addFragment(FragmentFactory.getDetailsFragment(user.getIdstr(), 1), getResources().getString(R.string.original));
        adapter.addFragment(FragmentFactory.getDetailsFragment(user.getIdstr(), 2), getResources().getString(R.string.picture));
        mViewPager.setAdapter(adapter);
        mTabLayout.setupWithViewPager(mViewPager);
    }

    private void initHeaderView() {
        iv_cover = (ImageView) findViewById(R.id.iv_cover);
        civ_avatar = (CircleImageView) findViewById(R.id.civ_avatar);
        tv_screen_name = (TextView) findViewById(R.id.tv_screen_name);
        tv_location = (TextView) findViewById(R.id.tv_location);
        tv_follower_num = (TextView) findViewById(R.id.tv_follower_num);
        tv_follow_num = (TextView) findViewById(R.id.tv_follow_num);
        tv_weibo_num = (TextView) findViewById(R.id.tv_weibo_num);
        tv_verified_reason = (TextView) findViewById(R.id.tv_verified_reason);
        tv_description = (TextView) findViewById(R.id.tv_description);
    }

    private Menu menu;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        this.menu = menu;
        getMenuInflater().inflate(R.menu.menu_user_details, menu);
        return super.onCreateOptionsMenu(menu);
    }

    private void initMenu() {
        if (user != null &&
                !SharePrefUtil.getString(this, "uid", "").equals(user.getIdstr())) {
            if (user.isFollowing()) {
                menu.getItem(0).setTitle(R.string.cancel_follow);
            } else {
                if ("m".equals(user.getGender())) {
                    menu.getItem(0).setTitle(R.string.follow_he);
                } else if ("f".equals(user.getGender())) {
                    menu.getItem(0).setTitle(R.string.follow_she);
                }
            }
        }

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    public static void actionStart(Context context, String screen_name) {
        Intent intent = new Intent(context, UserDetailsActivity.class);
        intent.putExtra("screen_name", screen_name);
        context.startActivity(intent);
    }

} public class MyApplication extends Application {

    private static Context context;
    private static ThreadPoolExecutor executor;
    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
    private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
    private static final int KEEP_ALIVE = 1;
    private static final BlockingQueue<Runnable> sPoolWorkQueue =
            new LinkedBlockingQueue<Runnable>(128);
    private static final ThreadFactory sThreadFactory = new ThreadFactory() {
        private final AtomicInteger mCount = new AtomicInteger(1);

        public Thread newThread(Runnable r) {
            return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
        }
    };
    private static RequestQueue mQueue;

    /**
     * 得到volley队列
     * @return
     */
    public static RequestQueue getRequestQueue() {
            return mQueue;
    }

    public static Context getContext() {
        return context;
    }

    public static ThreadPoolExecutor getExecutor() {
        return executor;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
                .threadPriority(Thread.NORM_PRIORITY - 1).denyCacheImageMultipleSizesInMemory()
                .memoryCache(new LruMemoryCache(2 * 1024 * 1024)).memoryCacheSize(2 * 1024 * 1024)
                .diskCacheFileNameGenerator(new Md5FileNameGenerator()).diskCacheSize(50 * 1024 * 1024)
                .diskCacheFileCount(300).tasksProcessingOrder(QueueProcessingType.LIFO)
                .build();
        ImageLoader.getInstance().init(config);
        executor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
                TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
        mQueue = Volley.newRequestQueue(context);
    }

} public class AppConstant {
    /**
     * App Key
     */
    public static final String APP_KEY = "2146675350";
    /**
     * App Secret
     */
    public static final String APP_SECRET = "2c990a9d6f2fd0a59a3f76da68663a58";
    /**
     * 默认回调页面
     */
    public static final String REDIRECT_URL = "https://api.weibo.com/oauth2/default.html";
    /**
     * OAuth2的authorize接口
     */
    public static final String AUTHORIZE_URL = "https://open.weibo.cn/oauth2/authorize";
    /**
     * OAuth2的access_token接口
     */
    public static final String ACCESS_TOKEN_URL = "https://api.weibo.com/oauth2/access_token";
    /**
     * 根据用户ID获取用户信息
     */
    public static final String USERS_SHOW_URL = "https://api.weibo.com/2/users/show.json";
    /**
     * 查询用户access_token的授权相关信息，包括授权时间，过期时间和scope权限。
     */
    public static final String GET_TOKEN_INFO_URL = "https://api.weibo.com/oauth2/get_token_info";
    /**
     * 获取当前登录用户及其所关注用户的最新微博
     */
    public static final String HOME_TIMELINE_URL = "https://api.weibo.com/2/statuses/home_timeline.json";
    /**
     * 搜索用户时的联想搜索建议
     */
    public static final String SEARCH_USER_URL = "https://api.weibo.com/2/search/suggestions/users.json";
    /**
     * 根据地理信息坐标返回实际地址
     */
    public static final String GEO_TO_ADDRESS_URL = "https://api.weibo.com/2/location/geo/geo_to_address.json";
    /**
     * 发布一条新微博
     */
    public static final String STATUSES_UPDATE_URL = "https://api.weibo.com/2/statuses/update.json";
    /**
     * 上传图片并发布一条新微博
     */
    public static final String STATUSES_UPLOAD_URL = "https://upload.api.weibo.com/2/statuses/upload.json";
    /**
     * 获取双向关注用户的最新微博
     */
    public static final String STATUSES_BILATERAL_TIMELINE_URL = "https://api.weibo.com/2/statuses/bilateral_timeline.json";
    /**
     * 转发一条微博
     */
    public static final String STATUSES_REPOST_URL = "https://api.weibo.com/2/statuses/repost.json";
    /**
     * 对一条微博进行评论
     */
    public static final String COMMENTS_CREATE_URL = "https://api.weibo.com/2/comments/create.json";
    /**
     * 获取用户的关注列表
     */
    public static final String FRIENDSHIPS_FRIENDS_URL = "https://api.weibo.com/2/friendships/friends.json";
    /**
     * 获取某个位置周边的动态
     */
    public static final String PLACE_NEARBY_TIMELINE_URL = "https://api.weibo.com/2/place/nearby_timeline.json";
    /**
     * 获取我的收藏
     */
    public static final String MY_FAVORITE_URL = "https://api.weibo.com/2/favorites.json";
    /**
     * 添加一条微博到收藏里
     */
    public static final String FAVORITE_CREATE_URL = "https://api.weibo.com/2/favorites/create.json";
    /**
     * 取消收藏一条微博
     */
    public static final String FAVORITE_DESTROY_URL = "https://api.weibo.com/2/favorites/destroy.json";
    /**
     * 根据微博ID返回某条微博的评论列表
     */
    public static final String COMMENTS_SHOW_URL = "https://api.weibo.com/2/comments/show.json";
    /**
     * 获取指定微博的转发微博列表
     */
    public static final String STATUSES_REPOST_TIMELINE_URL = "https://api.weibo.com/2/statuses/repost_timeline.json";
    /**
     * 批量获取指定微博的转发数评论数
     */
    public static final String STATUSES_COUNT_URL = "https://api.weibo.com/2/statuses/count.json";
    /**
     * 回复一条评论
     */
    public static final String COMMENTS_REPLY_URL = "https://api.weibo.com/2/comments/reply.json";
    /**
     * 获取某个用户最新发表的微博列表
     */
    public static final String STATUSES_USER_TIMELINE_URL = "https://api.weibo.com/2/statuses/user_timeline.json";
    /**
     * 返回最新的公共微博
     */
    public static final String STATUSES_PUBLIC_TIMELINE_URL = "https://api.weibo.com/2/statuses/public_timeline.json";
    /**
     * 获取某个用户的各种消息未读数
     */
    public static final String REMIND_UNREAD_COUNT_URL = "https://rm.api.weibo.com/2/remind/unread_count.json";
    /**
     * 授权回收接口，帮助开发者主动取消用户的授权。
     */
    public static final String OAUTH2_REVOKEOAUTH2_URL = "https://api.weibo.com/oauth2/revokeoauth2";
    /**
     * 获取最新的提到当前登录用户的评论，即@我的评论
     */
    public static final String COMMENTS_MENTIONS_URL = "https://api.weibo.com/2/comments/mentions.json";
    /**
     * 获取当前登录用户所接收到的评论列表
     */
    public static final String COMMENTS_TO_ME_URL = "https://api.weibo.com/2/comments/to_me.json";
    /**
     * 获取最新的提到登录用户的微博列表，即@我的微博
     */
    public static final String STATUSES_MENTIONS_URL = "https://api.weibo.com/2/statuses/mentions.json";
} public class Pic_urls implements Serializable {

    //图片url
    public String thumbnail_pic;

} public class Status implements Serializable {

    /**
     * "attitudes_count": 0,
     * "biz_feature": 0,
     * "comments_count": 0,
     * "created_at": "Fri Sep 25 08:48:07 +0800 2015",
     * "darwin_tags": [],
     * "favorited": false,
     * "id": 3890882283247737,
     * "idstr": "3890882283247737",
     * "in_reply_to_screen_name": "",
     * "in_reply_to_status_id": "",
     * "in_reply_to_user_id": "",
     * "mid": "3890882283247737",
     * "mlevel": 0,
     * "pic_urls": [],
     * "reposts_count": 0,
     * "retweeted_status": {
     * "attitudes_count": 48,
     * "biz_feature": 0,
     * "bmiddle_pic": "http://ww3.sinaimg.cn/bmiddle/80292f4bjw1ewe1t89okvj20c80cd0um.jpg",
     * "cardid": "vip_008",
     * "comments_count": 2,
     * "created_at": "Fri Sep 25 02:12:03 +0800 2015",
     * "darwin_tags": [],
     * "favorited": false,
     * "id": 3890782605461147,
     * "idstr": "3890782605461147",
     * "in_reply_to_screen_name": "",
     * "in_reply_to_status_id": "",
     * "in_reply_to_user_id": "",
     * "mid": "3890782605461147",
     * "mlevel": 0,
     * "original_pic": "http://ww3.sinaimg.cn/large/80292f4bjw1ewe1t89okvj20c80cd0um.jpg",
     * "pic_urls": [
     * {
     * "thumbnail_pic": "http://ww3.sinaimg.cn/thumbnail/80292f4bjw1ewe1t89okvj20c80cd0um.jpg"
     * },
     * {
     * "thumbnail_pic": "http://ww2.sinaimg.cn/thumbnail/80292f4bjw1ewe1t8w3uaj20c80cdgnb.jpg"
     * },
     * {
     * "thumbnail_pic": "http://ww2.sinaimg.cn/thumbnail/80292f4bjw1ewe1t9lk6kj20c80cdabt.jpg"
     * },
     * {
     * "thumbnail_pic": "http://ww2.sinaimg.cn/thumbnail/80292f4bjw1ewe1ta17xmj20c80cddhq.jpg"
     * },
     * {
     * "thumbnail_pic": "http://ww3.sinaimg.cn/thumbnail/80292f4bjw1ewe1tal109j20c80cd765.jpg"
     * },
     * {
     * "thumbnail_pic": "http://ww2.sinaimg.cn/thumbnail/80292f4bjw1ewe1taedmxj20c80cd40b.jpg"
     * },
     * {
     * "thumbnail_pic": "http://ww3.sinaimg.cn/thumbnail/80292f4bjw1ewe1taxrtqj20c80cdq4q.jpg"
     * },
     * {
     * "thumbnail_pic": "http://ww2.sinaimg.cn/thumbnail/80292f4bjw1ewe1tbfqnaj20c80cd761.jpg"
     * },
     * {
     * "thumbnail_pic": "http://ww4.sinaimg.cn/thumbnail/80292f4bjw1ewe1tbtfevj20c80cdq4q.jpg"
     * }
     * ],
     * "reposts_count": 89,
     * "source": "<a href="http://weibo.com/" rel="nofollow">微博 weibo.com</a>",
     * "source_allowclick": 0,
     * "source_type": 1,
     * "text": "处在低迷期，有些迷茫的童鞋看看--自我激励的十八种办法。分享，共勉",
     * "thumbnail_pic": "http://ww3.sinaimg.cn/thumbnail/80292f4bjw1ewe1t89okvj20c80cd0um.jpg",
     * "truncated": false,
     * "user": {
     * "ability_tags": "媒体评论,编辑,媒体营销,出品人",
     * "allow_all_act_msg": true,
     * "allow_all_comment": true,
     * "avatar_hd": "http://tp4.sinaimg.cn/2150182731/180/5613586011/1",
     * "avatar_large": "http://tp4.sinaimg.cn/2150182731/180/5613586011/1",
     * "bi_followers_count": 34,
     * "block_app": 1,
     * "block_word": 0,
     * "cardid": "vip_008",
     * "city": "1",
     * "class": 1,
     * "cover_image_phone": "http://ww1.sinaimg.cn/crop.0.0.640.640.640/a1d3feabjw1ecat4uqw77j20hs0hsacp.jpg",
     * "created_at": "Fri May 27 22:18:39 +0800 2011",
     * "credit_score": 80,
     * "description": "无责任爆料吐槽，关注后极易任性、躺枪、呆萌、自黑、喝醉、笑抽。。。。莫愁前路无知己，土豪我们在一起！不说了，先看个笑话压压惊。。。",
     * "domain": "zhuzhu3610",
     * "favourites_count": 12,
     * "follow_me": false,
     * "followers_count": 16708560,
     * "following": false,
     * "friends_count": 55,
     * "gender": "m",
     * "geo_enabled": false,
     * "id": 2150182731,
     * "idstr": "2150182731",
     * "lang": "zh-cn",
     * "location": "北京 东城区",
     * "mbrank": 5,
     * "mbtype": 12,
     * "name": "猪猪爱讲冷笑话",
     * "online_status": 0,
     * "pagefriends_count": 3,
     * "profile_image_url": "http://tp4.sinaimg.cn/2150182731/50/5613586011/1",
     * "profile_url": "zhuzhu3610",
     * "province": "11",
     * "ptype": 8,
     * "remark": "",
     * "screen_name": "猪猪爱讲冷笑话",
     * "star": 0,
     * "statuses_count": 136762,
     * "urank": 28,
     * "url": "",
     * "user_ability": 0,
     * "verified": true,
     * "verified_contact_email": "",
     * "verified_contact_mobile": "",
     * "verified_contact_name": "",
     * "verified_level": 3,
     * "verified_reason": "秒拍搞笑博主 微博签约自媒体",
     * "verified_reason_modified": "",
     * "verified_reason_url": "",
     * "verified_source": "",
     * "verified_source_url": "",
     * "verified_state": 0,
     * "verified_trade": "3374",
     * "verified_type": 0,
     * "weihao": ""
     * },
     * "userType": 0,
     * "visible": {
     * "list_id": 0,
     * "type": 0
     * }
     * },
     * "rid": "0_0_2_2666870349471306194",
     * "source": "<a href="http://app.weibo.com/t/feed/6G7MnG" rel="nofollow">三星GALAXY S4</a>",
     * "source_allowclick": 0,
     * "source_type": 1,
     * "text": "转发微博",
     * "truncated": false,
     * "user": {
     * "allow_all_act_msg": false,
     * "allow_all_comment": true,
     * "avatar_hd": "http://ww2.sinaimg.cn/crop.0.0.1080.1080.1024/d60812fajw8etvsx5jcc3j20u00u0tck.jpg",
     * "avatar_large": "http://tp3.sinaimg.cn/3590853370/180/5731337978/1",
     * "bi_followers_count": 8,
     * "block_app": 0,
     * "block_word": 0,
     * "city": "81",
     * "class": 1,
     * "created_at": "Fri Jul 12 15:53:01 +0800 2013",
     * "credit_score": 80,
     * "description": "这个你想不到的世界！",
     * "domain": "",
     * "favourites_count": 0,
     * "follow_me": true,
     * "followers_count": 28,
     * "following": true,
     * "friends_count": 156,
     * "gender": "m",
     * "geo_enabled": true,
     * "id": 3590853370,
     * "idstr": "3590853370",
     * "lang": "zh-cn",
     * "location": "重庆 江津市",
     * "mbrank": 0,
     * "mbtype": 0,
     * "name": "宛螖",
     * "online_status": 0,
     * "pagefriends_count": 0,
     * "profile_image_url": "http://tp3.sinaimg.cn/3590853370/50/5731337978/1",
     * "profile_url": "u/3590853370",
     * "province": "50",
     * "ptype": 0,
     * "remark": "",
     * "screen_name": "宛螖",
     * "star": 0,
     * "statuses_count": 202,
     * "urank": 10,
     * "url": "",
     * "user_ability": 0,
     * "verified": false,
     * "verified_reason": "",
     * "verified_reason_url": "",
     * "verified_source": "",
     * "verified_source_url": "",
     * "verified_trade": "",
     * "verified_type": -1,
     * "weihao": ""
     * },
     * "userType": 0,
     * "visible": {
     * "list_id": 0,
     * "type": 0
     * }
     */

    // 字符串型的微博ID
    private String idstr;
    // weibo创建时间
    private String created_at;
    // 微博ID
    private long id;
    // 微博MID
    private long mid;
    // weibo来源
    private String source;
    //是否已收藏，true：是，false：否
    private boolean favorited;
    //是否被截断，true：是，false：否
    private boolean truncated;
    //地理信息字段
    private Geo geo;
    // weibo转发数
    private int reposts_count;
    // weibo评论数
    private int comments_count;
    //表态数
    private int attitudes_count;
    // 微博作者的用户信息字段
    private User user;
    // 微博信息内容
    private String text;
    // 微博配图url
    private List<Pic_urls> pic_urls;
    // 转发微博状态
    private Retweeted_status retweeted_status;
    //原始图片地址，没有时不返回此字段
    private String original_pic;
    //中等尺寸图片地址，没有时不返回此字段
    private String bmiddle_pic;
    //缩略图片地址，没有时不返回此字段
    private String thumbnail_pic;
    private List<Annotations> annotations;
    //被转发微博是否被删除  "1"为是
    private String deleted;


    public String getIdstr() {
        return idstr;
    }

    public void setIdstr(String idstr) {
        this.idstr = idstr;
    }

    public String getCreated_at() {
        return created_at;
    }

    public void setCreated_at(String created_at) {
        this.created_at = created_at;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public long getMid() {
        return mid;
    }

    public void setMid(long mid) {
        this.mid = mid;
    }

    public String getSource() {
        return source;
    }

    public void setSource(String source) {
        this.source = source;
    }

    public boolean isFavorited() {
        return favorited;
    }

    public void setFavorited(boolean favorited) {
        this.favorited = favorited;
    }

    public boolean isTruncated() {
        return truncated;
    }

    public void setTruncated(boolean truncated) {
        this.truncated = truncated;
    }

    public Geo getGeo() {
        return geo;
    }

    public void setGeo(Geo geo) {
        this.geo = geo;
    }

    public int getReposts_count() {
        return reposts_count;
    }

    public void setReposts_count(int reposts_count) {
        this.reposts_count = reposts_count;
    }

    public int getComments_count() {
        return comments_count;
    }

    public void setComments_count(int comments_count) {
        this.comments_count = comments_count;
    }

    public int getAttitudes_count() {
        return attitudes_count;
    }

    public void setAttitudes_count(int attitudes_count) {
        this.attitudes_count = attitudes_count;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public List<Pic_urls> getPic_urls() {
        return pic_urls;
    }

    public void setPic_urls(List<Pic_urls> pic_urls) {
        this.pic_urls = pic_urls;
    }

    public Retweeted_status getRetweeted_status() {
        return retweeted_status;
    }

    public void setRetweeted_status(Retweeted_status retweeted_status) {
        this.retweeted_status = retweeted_status;
    }

    public String getOriginal_pic() {
        return original_pic;
    }

    public void setOriginal_pic(String original_pic) {
        this.original_pic = original_pic;
    }

    public String getBmiddle_pic() {
        return bmiddle_pic;
    }

    public void setBmiddle_pic(String bmiddle_pic) {
        this.bmiddle_pic = bmiddle_pic;
    }

    public String getThumbnail_pic() {
        return thumbnail_pic;
    }

    public void setThumbnail_pic(String thumbnail_pic) {
        this.thumbnail_pic = thumbnail_pic;
    }

    public List<Annotations> getAnnotations() {
        return annotations;
    }

    public void setAnnotations(List<Annotations> annotations) {
        this.annotations = annotations;
    }

    public String getDeleted() {
        return deleted;
    }

    public void setDeleted(String deleted) {
        this.deleted = deleted;
    }

    public class Retweeted_status implements Serializable {

        // 微博ID
        private long id;
        // 微博MID
        private long mid;
        // weibo创建时间
        private String created_at;
        //是否已收藏，true：是，false：否
        private boolean favorited;
        //是否被截断，true：是，false：否
        private boolean truncated;
        // 字符串型的微博ID
        private String idstr;
        // 微博信息内容
        private String text;
        // 微博作者的用户信息字段
        private User user;
        //地理信息字段
        private Geo geo;
        // weibo转发数
        private int reposts_count;
        // weibo评论数
        private int comments_count;
        //表态数
        private int attitudes_count;
        // 微博配图url
        private List<Pic_urls> pic_urls;
        //原始图片地址，没有时不返回此字段
        private String original_pic;
        //中等尺寸图片地址，没有时不返回此字段
        private String bmiddle_pic;
        //缩略图片地址，没有时不返回此字段
        private String thumbnail_pic;
        //被转发微博是否被删除  "1"为是
        private String deleted;

        public long getId() {
            return id;
        }

        public void setId(long id) {
            this.id = id;
        }

        public long getMid() {
            return mid;
        }

        public void setMid(long mid) {
            this.mid = mid;
        }

        public String getCreated_at() {
            return created_at;
        }

        public void setCreated_at(String created_at) {
            this.created_at = created_at;
        }

        public boolean isFavorited() {
            return favorited;
        }

        public void setFavorited(boolean favorited) {
            this.favorited = favorited;
        }

        public boolean isTruncated() {
            return truncated;
        }

        public void setTruncated(boolean truncated) {
            this.truncated = truncated;
        }

        public String getIdstr() {
            return idstr;
        }

        public void setIdstr(String idstr) {
            this.idstr = idstr;
        }

        public String getText() {
            return text;
        }

        public void setText(String text) {
            this.text = text;
        }

        public User getUser() {
            return user;
        }

        public void setUser(User user) {
            this.user = user;
        }

        public Geo getGeo() {
            return geo;
        }

        public void setGeo(Geo geo) {
            this.geo = geo;
        }

        public int getReposts_count() {
            return reposts_count;
        }

        public void setReposts_count(int reposts_count) {
            this.reposts_count = reposts_count;
        }

        public int getComments_count() {
            return comments_count;
        }

        public void setComments_count(int comments_count) {
            this.comments_count = comments_count;
        }

        public int getAttitudes_count() {
            return attitudes_count;
        }

        public void setAttitudes_count(int attitudes_count) {
            this.attitudes_count = attitudes_count;
        }

        public List<Pic_urls> getPic_urls() {
            return pic_urls;
        }

        public void setPic_urls(List<Pic_urls> pic_urls) {
            this.pic_urls = pic_urls;
        }

        public String getOriginal_pic() {
            return original_pic;
        }

        public void setOriginal_pic(String original_pic) {
            this.original_pic = original_pic;
        }

        public String getBmiddle_pic() {
            return bmiddle_pic;
        }

        public void setBmiddle_pic(String bmiddle_pic) {
            this.bmiddle_pic = bmiddle_pic;
        }

        public String getThumbnail_pic() {
            return thumbnail_pic;
        }

        public void setThumbnail_pic(String thumbnail_pic) {
            this.thumbnail_pic = thumbnail_pic;
        }

        public String getDeleted() {
            return deleted;
        }

        public void setDeleted(String deleted) {
            this.deleted = deleted;
        }
    }

    public class Annotations implements Serializable {
        private String client_mblogid;
        private Place place;
        private boolean mapi_request;
        private int shooting;

        public String getClient_mblogid() {
            return client_mblogid;
        }

        public void setClient_mblogid(String client_mblogid) {
            this.client_mblogid = client_mblogid;
        }

        public Place getPlace() {
            return place;
        }

        public void setPlace(Place place) {
            this.place = place;
        }

        public boolean isMapi_request() {
            return mapi_request;
        }

        public void setMapi_request(boolean mapi_request) {
            this.mapi_request = mapi_request;
        }

        public int getShooting() {
            return shooting;
        }

        public void setShooting(int shooting) {
            this.shooting = shooting;
        }

        public class Place implements Serializable {
            private double lat;
            private double lon;
            private String poiid;
            private String title;
            private String type;

            public double getLat() {
                return lat;
            }

            public void setLat(double lat) {
                this.lat = lat;
            }

            public double getLon() {
                return lon;
            }

            public void setLon(double lon) {
                this.lon = lon;
            }

            public String getPoiid() {
                return poiid;
            }

            public void setPoiid(String poiid) {
                this.poiid = poiid;
            }

            public String getTitle() {
                return title;
            }

            public void setTitle(String title) {
                this.title = title;
            }

            public String getType() {
                return type;
            }

            public void setType(String type) {
                this.type = type;
            }
        }

    }

} public class BitmapUtil {

    private static DisplayImageOptions options;

    public static DisplayImageOptions getDisplayImageOptions(int drawableId, boolean cacheInMemory, boolean cacheOnDisk) {
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(drawableId)
                .showImageOnFail(R.drawable.timeline_image_failure)
                .cacheInMemory(cacheInMemory)
                .cacheOnDisk(cacheOnDisk)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .build();
        return options;
    }


    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // 源图片的高度和宽度
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            // 计算出实际宽高和目标宽高的比率
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            // 选择宽和高中最小的比率作为inSampleSize的值，这样可以保证最终图片的宽和高
            // 一定都会大于等于目标的宽和高。
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }

    public static Bitmap decodeSampledBitmapFromUrl(String url, int reqWidth, int reqHeight) {
        // 第一次解析将inJustDecodeBounds设置为true，来获取图片大小
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(url, options);
        // 调用上面定义的方法计算inSampleSize值
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        // 使用获取到的inSampleSize值再次解析图片
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(url, options);
    }


} public class CommonUtil {

    /**
     * 如果转发数或评论数超过一万，就简写成 n万
     *
     * @param num
     * @return
     */
    public static String getNumString(int num) {
        if (num < 100000) {
            return String.valueOf(num);
        } else {
            int number = num / 10000;
            return number + "万";
        }
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 创建一个对话框
     */
    public static void createMessageAlertDialog(Context context, String title, String message,
                                                String negativeMessage, DialogInterface.OnClickListener negativeListener,
                                                String positiveMessage, DialogInterface.OnClickListener positiveListener, boolean cancelable) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(title).setMessage(message).setNegativeButton(negativeMessage, negativeListener).setPositiveButton(positiveMessage, positiveListener).setCancelable(cancelable).create().show();
    }

    public static void createMessageAlertDialog(Context context, int titleId, int messageId,
                                                int negativeMessageId, DialogInterface.OnClickListener negativeListener,
                                                int positiveMessageId, DialogInterface.OnClickListener positiveListener, boolean cancelable) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(titleId).setMessage(messageId).setNegativeButton(negativeMessageId, negativeListener).setPositiveButton(positiveMessageId, positiveListener).setCancelable(cancelable).create().show();
    }

    public static void createItemAlertDialog(Context context, CharSequence[] items,
                                             DialogInterface.OnClickListener listener, boolean cancelable) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setItems(items, listener).setCancelable(cancelable).create().show();
    }

    public static void createSingleChoiceAlertDialog(Context context, int itemsId, int checkedId,
                                                     DialogInterface.OnClickListener singleChoiceItemListener, String negativeMessage,
                                                     DialogInterface.OnClickListener negativeListener, String positiveMessage,
                                                     DialogInterface.OnClickListener positiveListener, boolean cancelable) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setSingleChoiceItems(itemsId, checkedId, singleChoiceItemListener)
                .setNegativeButton(negativeMessage, negativeListener).setPositiveButton(positiveMessage, positiveListener)
                .setCancelable(cancelable).create().show();
    }


    /**
     * 得到地理信息
     *
     * @param context
     * @return
     */
    public static Location getLocation(Context context) {
        String provider = null;
        Location location = null;
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        List<String> providers = locationManager.getProviders(true);
        if (providers.contains(LocationManager.GPS_PROVIDER)) {
            provider = LocationManager.GPS_PROVIDER;
        } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
            provider = LocationManager.NETWORK_PROVIDER;
        } else if (providers.contains(LocationManager.PASSIVE_PROVIDER)) {
            provider = LocationManager.PASSIVE_PROVIDER;
        } else {
            Toast.makeText(context, R.string.location_not_available, Toast.LENGTH_SHORT).show();
        }
        try {
            location = locationManager.getLastKnownLocation(provider);
        } catch (SecurityException e) {
            Toast.makeText(context, R.string.no_location_permission, Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
        return location;
    }

    /**
     * 获取相机最后一次拍照的url
     *
     * @param activity
     * @return
     */
    public static String getLatestCameraPicture(Activity activity) {
        String[] projection = new String[]{MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.DATA,
                MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME, MediaStore.Images.ImageColumns.DATE_TAKEN,
                MediaStore.Images.ImageColumns.MIME_TYPE};
        final Cursor cursor = activity.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null, null,
                MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC");
        if (cursor.moveToFirst()) {
            String path = cursor.getString(1);
            return path;
        }
        return null;
    }

    /**
     * 显示Toast
     *
     * @param context
     * @param message
     */
    public static void showToast(Context context, String message) {
        Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
    }

    public static void showToast(Context context, int resId) {
        Toast.makeText(context, resId, Toast.LENGTH_SHORT).show();
    }

    /**
     * @param context
     * @param milliseconds 震动的时长，单位是毫秒
     */
    public static void setVibrator(Context context, long milliseconds) {
        Vibrator vibator = (Vibrator) context.getSystemService(Service.VIBRATOR_SERVICE); // 取得震动服务
        vibator.vibrate(milliseconds);
    }

    /**
     * Context context
     * long[] pattern  ：自定义震动模式 。数组中数字的含义依次是[静止时长，震动时长，静止时长，震动时长。。。]时长的单位是毫秒
     * boolean isRepeat ： 是否反复震动，如果是true，反复震动，如果是false，只震动一次
     */
    public static void setVibrator(Context context, long[] pattern, boolean isRepeat) {
        Vibrator vib = (Vibrator) context.getSystemService(Service.VIBRATOR_SERVICE);
        vib.vibrate(pattern, isRepeat ? 1 : -1);
    }

    /**
     * 发布通知
     *
     * @param context
     * @param titleId
     * @param contentId
     * @param drawableId icon资源文件
     * @param cancelable
     */
    public static void showNotification(Context context, int titleId, int contentId, int drawableId, boolean cancelable) {
        NotificationManager notificationManager = (NotificationManager) context
                .getSystemService(context.NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        builder.setContentTitle(context.getString(titleId));
        builder.setContentText(context.getString(contentId));
        builder.setSmallIcon(drawableId);
        builder.setAutoCancel(cancelable);
        Notification mNotification = builder.build();
        notificationManager.notify(0, mNotification);
        if (SharePrefUtil.getBoolean(context, "vibrate_feedback", true)) {
            setVibrator(context, 300);
        }
    }

    /**
     * 显示Snackbar
     *
     * @param v
     * @param text
     * @param backgroundColor
     */
    public static void showSnackbar(View v, int text, int backgroundColor) {
        Snackbar sb = Snackbar.make(v, text, Snackbar.LENGTH_SHORT);
        sb.getView().setBackgroundColor(backgroundColor);
        sb.show();
    }

    public static void showSnackbar(View v, int text) {
        Snackbar.make(v, text, Snackbar.LENGTH_SHORT).show();
    }

    public static void showSnackbar(View v, int text, int backgroundColor, int length, int actionText, View.OnClickListener listener) {
        Snackbar sb = Snackbar.make(v, text, length).setAction(actionText, listener);
        sb.getView().setBackgroundColor(backgroundColor);
        sb.show();
    }

    public static void showPopupMenu(Context context, View v, int resId, PopupMenu.OnMenuItemClickListener listener) {
        PopupMenu mPopupMenu = new PopupMenu(context, v);
        mPopupMenu.getMenuInflater().inflate(resId, mPopupMenu.getMenu());
        mPopupMenu.setOnMenuItemClickListener(listener);
        mPopupMenu.show();
    }

    /**
     * 显示ProgressDialog
     *
     * @param context
     * @param stringResId
     * @param cancelable
     */
    public static ProgressDialog showProgressDialog(Context context, int stringResId, boolean cancelable) {
        ProgressDialog progressDialog = new ProgressDialog(context);
        progressDialog.setMessage(context.getResources().getString(stringResId));
        progressDialog.setCancelable(cancelable);
        progressDialog.show();
        return progressDialog;
    }

    /**
     * 把文本复制到粘贴板上
     *
     * @param context
     * @param text
     */
    public static void copyToClipboard(Context context, String text) {
        ClipboardManager clip = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        clip.setText(text); // 复制
    }

    /**
     * @param context
     * @param status
     */
    public static void shareWeibo(Context context, Status status) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        String title = context.getString(R.string.share_title);
        title = String.format(title, status.getUser().getScreen_name());
        intent.putExtra(Intent.EXTRA_SUBJECT, title);
        //设置分享的内容
        intent.putExtra(Intent.EXTRA_TEXT, status.getText());
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(Intent.createChooser(intent, context.getString(R.string.share)));
    }

    /**
     * 获取当前应用的版本号
     *
     * @param context
     * @return
     * @throws Exception
     */
    public static String getVersionName(Context context) {
        try {
            // 获取packagemanager的实例
            PackageManager packageManager = context.getPackageManager();
            // getPackageName()是你当前类的包名，0代表是获取版本信息
            PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            return packInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void openInBrowser(Context context, String url) {
        Uri uri = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        context.startActivity(intent);
    }

} public class DateUtils {
    /*
     * 将时间戳转为字符串 ，格式：yyyy-MM-dd HH:mm
     */
    public static String getStrTime_ymd_hm(String cc_time) {
        String re_StrTime = "";
        if (TextUtils.isEmpty(cc_time) || "null".equals(cc_time)) {
            return re_StrTime;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        // 例如：cc_time=1291778220
        long lcc_time = Long.valueOf(cc_time);
        re_StrTime = sdf.format(new Date(lcc_time * 1000L));
        return re_StrTime;

    }

    /*
     * 将时间戳转为字符串 ，格式：yyyy-MM-dd HH:mm:ss
     */
    public static String getStrTime_ymd_hms(String cc_time) {
        String re_StrTime = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 例如：cc_time=1291778220
        long lcc_time = Long.valueOf(cc_time);
        re_StrTime = sdf.format(new Date(lcc_time * 1000L));
        return re_StrTime;

    }

    /*
     * 将时间戳转为字符串 ，格式：yyyy.MM.dd
     */
    public static String getStrTime_ymd(String cc_time) {
        String re_StrTime = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
        // 例如：cc_time=1291778220
        long lcc_time = Long.valueOf(cc_time);
        re_StrTime = sdf.format(new Date(lcc_time * 1000L));
        return re_StrTime;
    }

    /*
     * 将时间戳转为字符串 ，格式：yyyy
     */
    public static String getStrTime_y(String cc_time) {
        String re_StrTime = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        // 例如：cc_time=1291778220
        long lcc_time = Long.valueOf(cc_time);
        re_StrTime = sdf.format(new Date(lcc_time * 1000L));
        return re_StrTime;
    }

    /*
     * 将时间戳转为字符串 ，格式：MM-dd
     */
    public static String getStrTime_md(String cc_time) {
        String re_StrTime = null;
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
        // 例如：cc_time=1291778220
        long lcc_time = Long.valueOf(cc_time);
        re_StrTime = sdf.format(new Date(lcc_time * 1000L));
        return re_StrTime;
    }

    /*
     * 将时间戳转为字符串 ，格式：HH:mm
     */
    public static String getStrTime_hm(String cc_time) {
        String re_StrTime = null;
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        // 例如：cc_time=1291778220
        long lcc_time = Long.valueOf(cc_time);
        re_StrTime = sdf.format(new Date(lcc_time * 1000L));
        return re_StrTime;
    }

    /*
     * 将时间戳转为字符串 ，格式：HH:mm:ss
     */
    public static String getStrTime_hms(String cc_time) {
        String re_StrTime = null;
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        // 例如：cc_time=1291778220
        long lcc_time = Long.valueOf(cc_time);
        re_StrTime = sdf.format(new Date(lcc_time * 1000L));
        return re_StrTime;
    }

    /*
     * 将时间戳转为字符串 ，格式：MM-dd HH:mm:ss
     */
    public static String getNewsDetailsDate(String cc_time) {
        String re_StrTime = null;
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm:ss");
        // 例如：cc_time=1291778220
        long lcc_time = Long.valueOf(cc_time);
        re_StrTime = sdf.format(new Date(lcc_time * 1000L));
        return re_StrTime;
    }

    /*
     * 将字符串转为时间戳
     */
    public static String getTime() {
        String re_time = null;
        long currentTime = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
        Date d;
        d = new Date(currentTime);
        long l = d.getTime();
        String str = String.valueOf(l);
        re_time = str.substring(0, 10);
        return re_time;
    }

    /*
     * 将时间戳转为字符串 ，格式：yyyy.MM.dd  星期几
     */
    public static String getSection(String cc_time) {
        String re_StrTime = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd  EEEE");
//		对于创建SimpleDateFormat传入的参数：EEEE代表星期，如“星期四”；MMMM代表中文月份，如“十一月”；MM代表月份，如“11”；
//		yyyy代表年份，如“2010”；dd代表天，如“25”
        // 例如：cc_time=1291778220
        long lcc_time = Long.valueOf(cc_time);
        re_StrTime = sdf.format(new Date(lcc_time * 1000L));
        return re_StrTime;
    }

    /**
     * 把字符串转化成时间
     *
     * @param time 例如： Mon Aug 31 09:54:22 +0800 2015
     * @return
     */
    public static String getWeiboDate(String time) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy", Locale.US);
        String format = "";
        try {
            if (TextUtils.isEmpty(time)) {
                return format;
            }
            Date date = simpleDateFormat.parse(time);
            format = RelativeDateFormat.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return format;
    }


} public class LogUtils {
	/** 日志输出级别NONE */

	public static final int LEVEL_NONE = 0;

	/** 日志输出级别V */

	public static final int LEVEL_VERBOSE = 1;

	/** 日志输出级别D */

	public static final int LEVEL_DEBUG = 2;

	/** 日志输出级别I */

	public static final int LEVEL_INFO = 3;

	/** 日志输出级别W */

	public static final int LEVEL_WARN = 4;

	/** 日志输出级别E */

	public static final int LEVEL_ERROR = 5;



	/** 日志输出时的TAG */

	private static String mTag = "koku";

	/** 是否允许输出log */

	private static int mDebuggable = LEVEL_ERROR;



	/** 用于记时的变量 */

	private static long mTimestamp = 0;





	/** 以级别为 d 的形式输出LOG */

	public static void v(String msg) {

		if (mDebuggable >= LEVEL_VERBOSE) {

			Log.v(mTag, msg);

		}

	}



	/** 以级别为 d 的形式输出LOG */

	public static void d(String msg) {

		if (mDebuggable >= LEVEL_DEBUG) {

			Log.d(mTag, msg);

		}

	}



	/** 以级别为 i 的形式输出LOG */

	public static void i(String msg) {

		if (mDebuggable >= LEVEL_INFO) {

			Log.i(mTag, msg);

		}

	}



	/** 以级别为 w 的形式输出LOG */

	public static void w(String msg) {

		if (mDebuggable >= LEVEL_WARN) {

			Log.w(mTag, msg);

		}

	}



	/** 以级别为 w 的形式输出Throwable */

	public static void w(Throwable tr) {

		if (mDebuggable >= LEVEL_WARN) {

			Log.w(mTag, "", tr);

		}

	}



	/** 以级别为 w 的形式输出LOG信息和Throwable */

	public static void w(String msg, Throwable tr) {

		if (mDebuggable >= LEVEL_WARN && null != msg) {

			Log.w(mTag, msg, tr);

		}

	}



	/** 以级别为 e 的形式输出LOG */

	public static void e(String msg) {

		if (mDebuggable >= LEVEL_ERROR) {

			Log.e(mTag, msg);

		}

	}



	/** 以级别为 e 的形式输出Throwable */

	public static void e(Throwable tr) {

		if (mDebuggable >= LEVEL_ERROR) {

			Log.e(mTag, "", tr);

		}

	}


	/** 以级别为 e 的形式输出LOG信息和Throwable */

	public static void e(String msg, Throwable tr) {

		if (mDebuggable >= LEVEL_ERROR && null != msg) {

			Log.e(mTag, msg, tr);

		}

	}


	/** 以级别为 e 的形式输出msg信息,附带时间戳，用于输出一个时间段结束点* @param msg 需要输出的msg */

	public static void elapsed(String msg) {

		long currentTime = System.currentTimeMillis();

		long elapsedTime = currentTime - mTimestamp;

		mTimestamp = currentTime;

		e("[Elapsed：" + elapsedTime + "]" + msg);

	}




} public class SharePrefUtil {

	private static String tag = SharePrefUtil.class.getSimpleName();
	private static SharedPreferences sp;
	private static final String SP_NAME = "config";

	/**
	 * 保存布尔值
	 * 
	 * @param context
	 * @param key
	 * @param value
	 */
	public static void saveBoolean(Context context, String key, boolean value) {
		if (sp == null)
			sp = context.getSharedPreferences(SP_NAME, 0);
		sp.edit().putBoolean(key, value).commit();
	}

	/**
	 * 保存字符串
	 * 
	 * @param context
	 * @param key
	 * @param value
	 */
	public static void saveString(Context context, String key, String value) {
		if (sp == null)
			sp = context.getSharedPreferences(SP_NAME, 0);
		sp.edit().putString(key, value).commit();

	}

	public static void clear(Context context) {
		if (sp == null)
			sp = context.getSharedPreferences(SP_NAME, 0);
		sp.edit().clear().commit();
	}

	/**
	 * 保存long型
	 * 
	 * @param context
	 * @param key
	 * @param value
	 */
	public static void saveLong(Context context, String key, long value) {
		if (sp == null)
			sp = context.getSharedPreferences(SP_NAME, 0);
		sp.edit().putLong(key, value).commit();
	}

	public static void saveStringSet(Context context, String key,
			Set<String> value) {
		if (sp == null)
			sp = context.getSharedPreferences(SP_NAME, 0);
		sp.edit().putStringSet(key, value).commit();
	}

	public static Set<String> getStringSet(Context context, String key,
			Set<String> defValue) {
		if (sp == null)
			sp = context.getSharedPreferences(SP_NAME, 0);
		return sp.getStringSet(key, defValue);
	}

	/**
	 * 保存int型
	 * 
	 * @param context
	 * @param key
	 * @param value
	 */
	public static void saveInt(Context context, String key, int value) {
		if (sp == null)
			sp = context.getSharedPreferences(SP_NAME, 0);
		sp.edit().putInt(key, value).commit();
	}

	/**
	 * 保存float型
	 * 
	 * @param context
	 * @param key
	 * @param value
	 */
	public static void saveFloat(Context context, String key, float value) {
		if (sp == null)
			sp = context.getSharedPreferences(SP_NAME, 0);
		sp.edit().putFloat(key, value).commit();
	}

	/**
	 * 获取字符值
	 * 
	 * @param context
	 * @param key
	 * @param defValue
	 * @return
	 */
	public static String getString(Context context, String key, String defValue) {
		if (sp == null)
			sp = context.getSharedPreferences(SP_NAME, 0);
		return sp.getString(key, defValue);
	}

	/**
	 * 获取int值
	 * 
	 * @param context
	 * @param key
	 * @param defValue
	 * @return
	 */
	public static int getInt(Context context, String key, int defValue) {
		if (sp == null)
			sp = context.getSharedPreferences(SP_NAME, 0);
		return sp.getInt(key, defValue);
	}

	/**
	 * 获取long值
	 * 
	 * @param context
	 * @param key
	 * @param defValue
	 * @return
	 */
	public static long getLong(Context context, String key, long defValue) {
		if (sp == null)
			sp = context.getSharedPreferences(SP_NAME, 0);
		return sp.getLong(key, defValue);
	}

	/**
	 * 获取float值
	 * 
	 * @param context
	 * @param key
	 * @param defValue
	 * @return
	 */
	public static float getFloat(Context context, String key, float defValue) {
		if (sp == null)
			sp = context.getSharedPreferences(SP_NAME, 0);
		return sp.getFloat(key, defValue);
	}

	/**
	 * 获取布尔值
	 * 
	 * @param context
	 * @param key
	 * @param defValue
	 * @return
	 */
	public static boolean getBoolean(Context context, String key,
			boolean defValue) {
		if (sp == null)
			sp = context.getSharedPreferences(SP_NAME, 0);
		return sp.getBoolean(key, defValue);
	}

	/**
	 * 将对象进行base64编码后保存到SharePref中
	 * 
	 * @param context
	 * @param key
	 * @param object
	 */
	public static void saveObj(Context context, String key, Object object) {
		if (sp == null)
			sp = context.getSharedPreferences(SP_NAME, 0);

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutputStream oos = null;
		try {
			oos = new ObjectOutputStream(baos);
			oos.writeObject(object);
			// 将对象的转为base64码
			String objBase64 = new String(Base64.encode(baos.toByteArray(),
					Base64.DEFAULT));

			sp.edit().putString(key, objBase64).commit();
			oos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 将SharePref中经过base64编码的对象读取出来
	 * 
	 * @param context
	 * @param key
	 * @return
	 */
	public static Object getObj(Context context, String key) {
		if (sp == null)
			sp = context.getSharedPreferences(SP_NAME, 0);
		String objBase64 = sp.getString(key, null);
		if (TextUtils.isEmpty(objBase64))
			return null;

		// 对Base64格式的字符串进行解码
		byte[] base64Bytes = Base64
				.decode(objBase64.getBytes(), Base64.DEFAULT);
		ByteArrayInputStream bais = new ByteArrayInputStream(base64Bytes);

		ObjectInputStream ois;
		Object obj = null;
		try {
			ois = new ObjectInputStream(bais);
			obj = (Object) ois.readObject();
			ois.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return obj;
	}

} public class StringUtils {

    // 定义正则表达式
    private static final String AT = "@[\u4e00-\u9fa5-\\w]+";// @人
    private static final String TOPIC = "#[\u4e00-\u9fa5\\w]+#";// ##话题
    private static final String EMOJI = "\\[[\u4e00-\u9fa5\\w]+\\]";// 表情
    private static final String URL = "http://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";// url

    private static final String REGEX = "(" + AT + ")|(" + TOPIC + ")|(" + EMOJI + ")|(" + URL + ")";

    /**
     * 把String转化为List
     *
     * @param pic_urls
     * @return
     */
    public static List<String> convertStringToList(String pic_urls) {
        List<String> list = new ArrayList<>();
        String[] arrays = pic_urls.split(",");
        int size = arrays.length;
        for (int i = 0; i < size; i++) {
            list.add(arrays[i]);
        }
        return list;
    }

    /**
     * 把String转化为List
     *
     * @param list
     * @return
     */
    public static String convertListToString(List<String> list) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            builder.append(list.get(i) + ",");
        }
        return builder.toString();
    }

    /**
     * 设置微博内容样式
     *
     * @param context
     * @param source
     * @param textView
     * @return
     */
    public static SpannableString getWeiBoContent(final Context context, String source, TextView textView) {
        SpannableString spannableString = new SpannableString(source);

        //设置正则
        Pattern pattern = Pattern.compile(REGEX);
        Matcher matcher = pattern.matcher(spannableString);

        if (matcher.find()) {
            // 要实现文字的点击效果，这里需要做特殊处理
            textView.setMovementMethod(LinkMovementMethod.getInstance());
            // 重置正则位置
            matcher.reset();
        }

        while (matcher.find()) {
            // 根据group的括号索引，可得出具体匹配哪个正则(0代表全部，1代表第一个括号)
            final String at = matcher.group(1);
            final String topic = matcher.group(2);
            String emoji = matcher.group(3);
            final String url = matcher.group(4);

            // 处理@符号
            if (at != null) {
                //获取匹配位置
                int start = matcher.start(1);
                int end = start + at.length();
                MyClickableSpan clickableSpan = new MyClickableSpan(context) {
                    @Override
                    public void onClick(View widget) {
                        //点击了用户跳转事件
                        LogUtils.i("点击了用户：" + at);
                        UserDetailsActivity.actionStart(context, at.substring(1));
                    }
                };
                spannableString.setSpan(clickableSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }

            // 处理话题##符号
            if (topic != null) {
                int start = matcher.start(2);
                int end = start + topic.length();
                MyClickableSpan clickableSpan = new MyClickableSpan(context) {

                    @Override
                    public void onClick(View widget) {
                        Toast.makeText(context, "点击了话题：" + topic, Toast.LENGTH_LONG).show();
                    }
                };
                spannableString.setSpan(clickableSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            if (emoji != null) {
                int start = matcher.start(3);
                int end = start + emoji.length();

                byte[] emotion = EmotionsDB.getEmotion(emoji);
                if (emotion != null) {
                    Bitmap bitmap = BitmapFactory.decodeByteArray(emotion, 0, emotion.length);
                    if (bitmap != null) {
                        // 设置表情
                        int size = (int) textView.getTextSize();
                        // 压缩Bitmap 设置为字体大小的1.5倍
                        bitmap = Bitmap.createScaledBitmap(bitmap, (int) (size * 1.5), (int) (size * 1.5), true);

                        ImageSpan imageSpan = new ImageSpan(context, bitmap);
                        spannableString.setSpan(imageSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    }
                }
            }

            // 处理url地址
            if (url != null) {
                int start = matcher.start(4);
                int end = start + url.length();
                MyClickableSpan clickableSpan = new MyClickableSpan(context) {
                    @Override
                    public void onClick(View widget) {
                        LogUtils.i("点击了网址：" + url);
                        if (SharePrefUtil.getBoolean(context, "built-in_browser", true)) {
                            WebViewActivity.actionStart(context, url);
                        } else {
                            CommonUtil.openInBrowser(context, url);
                        }
                    }
                };
                spannableString.setSpan(clickableSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }

        return spannableString;
    }

    /**
     * 继承ClickableSpan复写updateDrawState方法，自定义所需样式
     *
     * @author Rabbit_Lee
     */
    public static class MyClickableSpan extends ClickableSpan {

        private Context context;

        public MyClickableSpan(Context context) {
            this.context = context;
        }

        @Override
        public void onClick(View widget) {

        }

        @Override
        public void updateDrawState(TextPaint ds) {
            super.updateDrawState(ds);
            ds.setColor(context.getResources().getColor(R.color.span_text_color));
            ds.setUnderlineText(false);
        }

    }

}
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.SpannableString;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.yuqirong.koku.R;
import com.yuqirong.koku.activity.ImageBrowserActivity;
import com.yuqirong.koku.activity.MainActivity;
import com.yuqirong.koku.activity.MyFavoriteActivity;
import com.yuqirong.koku.activity.NearlyDynamicActivity;
import com.yuqirong.koku.activity.PublishActivity;
import com.yuqirong.koku.activity.UserDetailsActivity;
import com.yuqirong.koku.application.MyApplication;
import com.yuqirong.koku.constant.AppConstant;
import com.yuqirong.koku.entity.Pic_urls;
import com.yuqirong.koku.entity.Status;
import com.yuqirong.koku.util.BitmapUtil;
import com.yuqirong.koku.util.CommonUtil;
import com.yuqirong.koku.util.DateUtils;
import com.yuqirong.koku.util.LogUtils;
import com.yuqirong.koku.util.SharePrefUtil;
import com.yuqirong.koku.util.StringUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
package com.yuqirong.koku.adapter;




/**
 * 微博适配器
 * Created by Anyway on 2015/8/30.
 */
public class WeiboRecycleViewAdapter extends LoadMoreAdapter<Status> {

    private Context context;
    private ImageLoader imageLoader;
    private static DisplayImageOptions options;
    private static DisplayImageOptions ninepic_options;

    public static final String AT = "@";
    private static final int[] IMAGEVIEW_IDS = new int[]{R.id.iv_01, R.id.iv_02, R.id.iv_03, R.id.iv_04, R.id.iv_05, R.id.iv_06, R.id.iv_07, R.id.iv_08, R.id.iv_09};
    private Status status;
    private View view;

    public WeiboRecycleViewAdapter(Context context) {
        this.context = context;
        imageLoader = ImageLoader.getInstance();
        options = BitmapUtil.getDisplayImageOptions(R.drawable.img_empty_avatar, true, true);
        ninepic_options = BitmapUtil.getDisplayImageOptions(R.drawable.thumbnail_default, true, true);
    }

    @Override
    public RecyclerView.ViewHolder createCustomViewHolder(ViewGroup parent, int viewType) {
        view = parent;
        View view = LayoutInflater.from(context).inflate(R.layout.weibo_original_item, parent, false);
        WeiboViewHolder holder = new WeiboViewHolder(view);
        return holder;
    }

    @Override
    public void bindCustomViewHolder(RecyclerView.ViewHolder holder, final int position) {
        status = list.get(position);
        WeiboViewHolder viewHolder = (WeiboViewHolder) holder;
        //创建监听器实例
        viewHolder.onMenuItemClickListener = new MyOnMenuItemClickListener(position);
        viewHolder.onClickListener = new WeiboWidghtOnClickListener(position, viewHolder.onMenuItemClickListener);
        if (!TextUtils.isEmpty(status.getDeleted()) && status.getDeleted().equals("1")) {
            SpannableString weiBoContent = StringUtils.getWeiBoContent(context, status.getText(), viewHolder.tv_text);
            viewHolder.tv_text.setText(weiBoContent);
        } else {
            if (SharePrefUtil.getBoolean(context, "user_remark", true)) {
                viewHolder.tv_screen_name.setText(status.getUser().getName());
            } else {
                viewHolder.tv_screen_name.setText(status.getUser().getScreen_name());
            }
            imageLoader.displayImage(status.getUser().getProfile_image_url(), viewHolder.iv_avatar, options);
            viewHolder.tv_time.setText(DateUtils.getWeiboDate(status.getCreated_at()));