cn.zhangls.android.weibo.utils.TextUtil.java Source code

Java tutorial

Introduction

Here is the source code for cn.zhangls.android.weibo.utils.TextUtil.java

Source

/*
 * MIT License
 *
 * Copyright (c) 2017 zhangls2014
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package cn.zhangls.android.weibo.utils;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.ImageSpan;
import android.util.Log;

import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.zhangls.android.weibo.Constants;
import cn.zhangls.android.weibo.R;
import cn.zhangls.android.weibo.TextClickableSpan;

/**
 * Created by zhangls on 2016/11/8.
 * <p>
 * ?
 */

public class TextUtil {

    /**
     * ??
     */
    public static final int CLICK_TYPE_USER_NAME = 1;
    /**
     * ?
     */
    public static final int CLICK_TYPE_TOPIC = 2;
    /**
     * 
     */
    public static final int CLICK_TYPE_LINK = 3;

    /**
     * ??
     */
    public static class StrHolder {
        private String Name;
        private int start;
        private int end;

        public int getEnd() {
            return end;
        }

        public void setEnd(int end) {
            this.end = end;
        }

        public String getName() {
            return Name;
        }

        public void setName(String name) {
            Name = name;
        }

        public int getStart() {
            return start;
        }

        public void setStart(int start) {
            this.start = start;
        }
    }

    /**
     * ??
     * <p>
     * ?????
     *
     * ClickableSpan ?????
     *
     * @param str  
     * @param colorId 
     * @param textSize ?
     * @return 
     */
    public static SpannableStringBuilder convertText(Context context, String str, int colorId, int textSize) {
        // ??
        SpannableStringBuilder builder = new SpannableStringBuilder(str);
        // 
        ArrayList<StrHolder> emojiList = findRegexString(str, Constants.RegularExpression.EmojiRegex);
        replaceEmoji(context, builder, emojiList, textSize);
        // ?
        ArrayList<StrHolder> topicList = findRegexString(str, Constants.RegularExpression.TopicRegex);
        showLightString(context, builder, topicList, colorId, CLICK_TYPE_TOPIC);
        // 
        ArrayList<StrHolder> nameList = findRegexString(str, Constants.RegularExpression.NameRegex);
        showLightString(context, builder, nameList, colorId, CLICK_TYPE_USER_NAME);
        //
        ArrayList<StrHolder> linkList = findRegexString(str, Constants.RegularExpression.HttpRegex);
        showLightString(context, builder, linkList, colorId, CLICK_TYPE_LINK);

        return builder;
    }

    /**
     * ??
     *
     * @param str 
     * @param regex ?
     * @return StrHolder ??
     */
    public static ArrayList<StrHolder> findRegexString(String str, String regex) {
        //?
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);

        ArrayList<StrHolder> arrayList = new ArrayList<>();

        while (matcher.find()) {//?
            String key = matcher.group();// ??
            StrHolder strHolder = new StrHolder();
            strHolder.setName(key);
            strHolder.setStart(matcher.start());
            strHolder.setEnd(matcher.end());
            arrayList.add(strHolder);
        }
        return arrayList;
    }

    /**
     * ????id ?getResId("icon", R.drawable.class);
     *
     * @param variableName variableName
     * @param c            ??
     * @return ?Id
     */
    private static int getResId(String variableName, Class<?> c) {
        try {
            Field idField = c.getDeclaredField(variableName);
            return idField.getInt(idField);
        } catch (Exception e) {
            System.out.println("===NoSuchFie===:" + variableName != null ? variableName : "null");
            return -1;
        }
    }

    /**
     * ??
     *
     * @param createTime ?EEE MMM dd HH:mm:ss z yyyy
     * @return ?
     */
    public static String convertCreateTime(Context context, String createTime) {
        String returnTime = "";
        SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm", Locale.ENGLISH);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm", Locale.ENGLISH);
        try {
            Date time = format.parse(createTime);
            Date curDate = new Date(System.currentTimeMillis());//??

            long timeDifference = curDate.getTime() - time.getTime();//
            long second = timeDifference / 1000;// 
            long min = second / 60;// 
            long hour = min / 60;// 
            long day = hour / 24;// 

            if (min >= 0 && min < 1) {
                returnTime = context.getResources().getString(R.string.weibo_container_create_time_just_now);
            } else if (min >= 1 && min <= 60) {
                returnTime = min + context.getResources().getString(R.string.weibo_container_create_time_mins_ago);
            } else if (hour >= 1 && hour <= 24) {
                returnTime = hour
                        + context.getResources().getString(R.string.weibo_container_create_time_hours_ago);
            } else if (day >= 1 && day <= 2) {
                returnTime = context.getResources().getString(R.string.weibo_container_create_time_yesterday)
                        + timeFormat.format(time);
            } else if (dateFormat.format(curDate).substring(0, 2).equals(dateFormat.format(time).substring(0, 2))) {// ???
                returnTime = dateFormat.format(time).substring(3, 14);
            } else if (!dateFormat.format(curDate).substring(0, 2)
                    .equals(dateFormat.format(time).substring(0, 2))) {// ????
                returnTime = dateFormat.format(time);
            }
        } catch (ParseException e) {
            e.printStackTrace();
            returnTime = createTime;
        }
        return returnTime;
    }

    /**
     * 
     *
     * @param context   
     * @param builder   SpannableStringBuilder
     * @param arrayList ??
     */
    private static void showLightString(Context context, SpannableStringBuilder builder,
            ArrayList<StrHolder> arrayList, int colorId, int clickType) {
        if (arrayList != null && arrayList.size() > 0) {
            for (StrHolder item : arrayList) {
                ClickableSpan clickableSpan = new TextClickableSpan(context, item.getName(), clickType);
                builder.setSpan(clickableSpan, item.getStart(), item.getEnd(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
                // ForegroundColorSpan 
                ForegroundColorSpan colorSpan = new ForegroundColorSpan(colorId);
                builder.setSpan(colorSpan, item.getStart(), item.getEnd(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
            }
        }
    }

    /**
     * ?? emoji 
     *
     * @param context   
     * @param builder   SpannableStringBuilder
     * @param arrayList ??
     */
    private static void replaceEmoji(Context context, SpannableStringBuilder builder,
            ArrayList<StrHolder> arrayList, int textSze) {
        if (arrayList != null && arrayList.size() > 0) {
            PinyinUtil pinyinUtils = PinyinUtil.getInstance(context);
            for (StrHolder emoji : arrayList) {
                if (!emoji.getName().isEmpty()) {
                    // ??? [] ?? [erha]
                    if (emoji.getName().length() <= 2) {
                        return;
                    }
                    String substring = emoji.getName().substring(1, emoji.getName().length() - 1);
                    String pinyin = pinyinUtils.getPinyin(substring);
                    Log.d("emoji", "replaceEmoji: ======" + substring + "======" + pinyin);
                    if (getResId(pinyin, R.drawable.class) != -1) {
                        //????Id
                        Drawable drawable = ContextCompat.getDrawable(context, getResId(pinyin, R.drawable.class));
                        drawable.setBounds(0, 0, textSze, textSze);
                        //??ImageSpan
                        ImageSpan imageSpan = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
                        // ??23????startend
                        // ???,[5,12)5125?12
                        builder.setSpan(imageSpan, emoji.getStart(), emoji.getEnd(),
                                Spannable.SPAN_INCLUSIVE_INCLUSIVE);
                    }
                }
            }
        }
    }
}