zoukankan      html  css  js  c++  java
  • Android开发系列(十七)QQ聊天之Android显示Gif ——在TextView中添加动态表情

      好久没有对这一系列进行更新了,不知道各位亲的Android功力有没有更上一层楼?本来并没有打算在这段时间发表新的博客,但是由于这一两天找到了一个能够让Android上显示Gif图片的方法,这样一来,寒假里没有解决的QQ添加动态表情的问题便有了一个初步的解决方法。下面进入正题~ PS:本讲源码地址在文末。

         本节的目标是对TextView进行修改,最终实现在TextView插入动态图片的效果。QQ聊天界面的动态表情、大表情、或者一些第三方的动态图就是实现了这个效果。

         老规矩首先上一个效果图:

          

        那两只小鸡其实都是动图,只不过这里不好发Gif,你也可以注意到左右两图的小黄鸡是不一样的,说明它在动~

         然后讲一下基本原理:

         谷歌官方并没有给出Gif的显示控件(虽然我想在高霸上的谷歌眼中这不过是随便敲敲键盘的事儿),网络上给的解决思路,基本上可以分为两个方向:

         一、使用Movie类,将Gif当成视频来播放。 经验证之后发现这种方法并不靠谱,播放的Gif不是花屏就是完全黑屏,而且另外一个缺点是可操作性不强,比如就没有办法把它嵌在TextView中。因此,不推荐用此方法,各位所有为此困扰的建议果断抛弃这种思路。

         二、将Gif文件 分解成多帧图片,然后由一个线程控制ImageView或者ImageSpan按照一定的时间间隔循环加载这几帧图片。

              而对于如何将Gif图片分解成多帧图片又有两种思路:一个是人工采用一个软件将gif图片分解成多个帧,然后把这每一帧都放进资源文件夹中,然后按照上面的方法进行加载,这种方法虽然看起来很笨,但是效果最流畅,我估计较早版本的手机QQ可能这样干过==    另外一种思路就是采用工具类进行即时解码,这种方法看起来比较高端,但对内存资源的消耗比较多,还有一个关键的问题是现在很难找到一个完美的工具类可以对Gif图片有较好的解码,我想腾讯肯定会有,但是不见得会开源..现在code.google.com上一个gifView.jar的工具包,有兴趣可以去网上搜一下,这个工具包里面对于gif的软解码还是比较全,当然也不完美。

         在本项目中采用的也是第二种思路,即采用一个工具类GifOpenHelper.java对gif进行解码,将生成的一组Bitmap对象存储在一个ArrayList<Bitmap>中,然后由线程控制加载。这里首先声明这个工具类不是我原创的,也有一些缺陷,首先给出这个类:

    package com.example.textactivity;
    
    import java.io.InputStream;
    import java.util.Vector;
    
    import android.graphics.Bitmap;
    import android.graphics.Bitmap.Config;
    
    //Handler for read & extract Bitmap from *.gif
    public class GifOpenHelper {
    
        // to store *.gif data, Bitmap & delay
        class GifFrame {
            // to access image & delay w/o interface
            public Bitmap image;
            public int delay;
    
            public GifFrame(Bitmap im, int del) {
                image = im;
                delay = del;
            }
    
        }
    
        // to define some error type
        public static final int STATUS_OK = 0;
        public static final int STATUS_FORMAT_ERROR = 1;
        public static final int STATUS_OPEN_ERROR = 2;
    
        protected int status;
    
        protected InputStream in;
    
        protected int width; // full image width
        protected int height; // full image height
        protected boolean gctFlag; // global color table used
        protected int gctSize; // size of global color table
        protected int loopCount = 1; // iterations; 0 = repeat forever
    
        protected int[] gct; // global color table
        protected int[] lct; // local color table
        protected int[] act; // active color table
    
        protected int bgIndex; // background color index
        protected int bgColor; // background color
        protected int lastBgColor; // previous bg color
        protected int pixelAspect; // pixel aspect ratio
    
        protected boolean lctFlag; // local color table flag
        protected boolean interlace; // interlace flag
        protected int lctSize; // local color table size
    
        protected int ix, iy, iw, ih; // current image rectangle
        protected int lrx, lry, lrw, lrh;
        protected Bitmap image; // current frame
        protected Bitmap lastImage; // previous frame
        protected int frameindex = 0;
    
        public int getFrameindex() {
            return frameindex;
        }
    
        public void setFrameindex(int frameindex) {
            this.frameindex = frameindex;
            if (frameindex > frames.size() - 1) {
                frameindex = 0;
            }                        //设置循环播放
        }
    
        protected byte[] block = new byte[256]; // current data block
        protected int blockSize = 0; // block size
    
        // last graphic control extension info
        protected int dispose = 0;
        // 0=no action; 1=leave in place; 2=restore to bg; 3=restore to prev
        protected int lastDispose = 0;
        protected boolean transparency = false; // use transparent color
        protected int delay = 0; // delay in milliseconds
        protected int transIndex; // transparent color index
    
        protected static final int MaxStackSize = 4096;
        // max decoder pixel stack size
    
        // LZW decoder working arrays
        protected short[] prefix;
        protected byte[] suffix;
        protected byte[] pixelStack;
        protected byte[] pixels;
    
        protected Vector<GifFrame> frames; // frames read from current file
        protected int frameCount;
    
        // to get its Width / Height
        public int getWidth() {
            return width;
        }
    
        public int getHeigh() {
            return height;
        }
    
        /**
         * Gets display duration for specified frame.
         * 
         * @param n
         *            int index of frame
         * @return delay in milliseconds
         */
        public int getDelay(int n) {
            delay = -1;
            if ((n >= 0) && (n < frameCount)) {
                delay = ((GifFrame) frames.elementAt(n)).delay;
            }
            return delay;
        }
    
        public int getFrameCount() {
            return frameCount;
        }
    
        public Bitmap getImage() {
            return getFrame(0);
        }
    
        public int getLoopCount() {
            return loopCount;
        }
    
        protected void setPixels() {
            int[] dest = new int[width * height];
            // fill in starting image contents based on last image's dispose code
            if (lastDispose > 0) {
                if (lastDispose == 3) {
                    // use image before last
                    int n = frameCount - 2;
                    if (n > 0) {
                        lastImage = getFrame(n - 1);
                    } else {
                        lastImage = null;
                    }
                }
                if (lastImage != null) {
                    lastImage.getPixels(dest, 0, width, 0, 0, width, height);
                    // copy pixels
                    if (lastDispose == 2) {
                        // fill last image rect area with background color
                        int c = 0;
                        if (!transparency) {
                            c = lastBgColor;
                        }
                        for (int i = 0; i < lrh; i++) {
                            int n1 = (lry + i) * width + lrx;
                            int n2 = n1 + lrw;
                            for (int k = n1; k < n2; k++) {
                                dest[k] = c;
                            }
                        }
                    }
                }
            }
    
            // copy each source line to the appropriate place in the destination
            int pass = 1;
            int inc = 8;
            int iline = 0;
            for (int i = 0; i < ih; i++) {
                int line = i;
                if (interlace) {
                    if (iline >= ih) {
                        pass++;
                        switch (pass) {
                        case 2:
                            iline = 4;
                            break;
                        case 3:
                            iline = 2;
                            inc = 4;
                            break;
                        case 4:
                            iline = 1;
                            inc = 2;
                        }
                    }
                    line = iline;
                    iline += inc;
                }
                line += iy;
                if (line < height) {
                    int k = line * width;
                    int dx = k + ix; // start of line in dest
                    int dlim = dx + iw; // end of dest line
                    if ((k + width) < dlim) {
                        dlim = k + width; // past dest edge
                    }
                    int sx = i * iw; // start of line in source
                    while (dx < dlim) {
                        // map color and insert in destination
                        int index = ((int) pixels[sx++]) & 0xff;
                        int c = act[index];
                        if (c != 0) {
                            dest[dx] = c;
                        }
                        dx++;
                    }
                }
            }
            image = Bitmap.createBitmap(dest, width, height, Config.RGB_565);
        }
    
        public Bitmap getFrame(int n) {
            Bitmap im = null;
            if ((n >= 0) && (n < frameCount)) {
                im = ((GifFrame) frames.elementAt(n)).image;
            }
            return im;
        }
    
        public Bitmap nextBitmap() {
            frameindex++;
            if (frameindex > frames.size() - 1) {
                frameindex = 0;
            }
            return ((GifFrame) frames.elementAt(frameindex)).image;
        }
    
        public int nextDelay() {
            return ((GifFrame) frames.elementAt(frameindex)).delay;
        }
    
        // to read & parse all *.gif stream
        public int read(InputStream is) {
            init();
            if (is != null) {
                in = is;
    
                readHeader();
                if (!err()) {
                    readContents();
                    if (frameCount < 0) {
                        status = STATUS_FORMAT_ERROR;
                    }
                }
            } else {
                status = STATUS_OPEN_ERROR;
            }
            try {
                is.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return status;
        }
    
        protected void decodeImageData() {
            int NullCode = -1;
            int npix = iw * ih;
            int available, clear, code_mask, code_size, end_of_information, in_code, old_code, bits, code, count, i, datum, data_size, first, top, bi, pi;
    
            if ((pixels == null) || (pixels.length < npix)) {
                pixels = new byte[npix]; // allocate new pixel array
            }
            if (prefix == null) {
                prefix = new short[MaxStackSize];
            }
            if (suffix == null) {
                suffix = new byte[MaxStackSize];
            }
            if (pixelStack == null) {
                pixelStack = new byte[MaxStackSize + 1];
            }
            // Initialize GIF data stream decoder.
            data_size = read();
            clear = 1 << data_size;
            end_of_information = clear + 1;
            available = clear + 2;
            old_code = NullCode;
            code_size = data_size + 1;
            code_mask = (1 << code_size) - 1;
            for (code = 0; code < clear; code++) {
                prefix[code] = 0;
                suffix[code] = (byte) code;
            }
    
            // Decode GIF pixel stream.
            datum = bits = count = first = top = pi = bi = 0;
            for (i = 0; i < npix;) {
                if (top == 0) {
                    if (bits < code_size) {
                        // Load bytes until there are enough bits for a code.
                        if (count == 0) {
                            // Read a new data block.
                            count = readBlock();
                            if (count <= 0) {
                                break;
                            }
                            bi = 0;
                        }
                        datum += (((int) block[bi]) & 0xff) << bits;
                        bits += 8;
                        bi++;
                        count--;
                        continue;
                    }
                    // Get the next code.
                    code = datum & code_mask;
                    datum >>= code_size;
                    bits -= code_size;
    
                    // Interpret the code
                    if ((code > available) || (code == end_of_information)) {
                        break;
                    }
                    if (code == clear) {
                        // Reset decoder.
                        code_size = data_size + 1;
                        code_mask = (1 << code_size) - 1;
                        available = clear + 2;
                        old_code = NullCode;
                        continue;
                    }
                    if (old_code == NullCode) {
                        pixelStack[top++] = suffix[code];
                        old_code = code;
                        first = code;
                        continue;
                    }
                    in_code = code;
                    if (code == available) {
                        pixelStack[top++] = (byte) first;
                        code = old_code;
                    }
                    while (code > clear) {
                        pixelStack[top++] = suffix[code];
                        code = prefix[code];
                    }
                    first = ((int) suffix[code]) & 0xff;
                    // Add a new string to the string table,
                    if (available >= MaxStackSize) {
                        break;
                    }
                    pixelStack[top++] = (byte) first;
                    prefix[available] = (short) old_code;
                    suffix[available] = (byte) first;
                    available++;
                    if (((available & code_mask) == 0)
                            && (available < MaxStackSize)) {
                        code_size++;
                        code_mask += available;
                    }
                    old_code = in_code;
                }
    
                // Pop a pixel off the pixel stack.
                top--;
                pixels[pi++] = pixelStack[top];
                i++;
            }
            for (i = pi; i < npix; i++) {
                pixels[i] = 0; // clear missing pixels
            }
        }
    
        protected boolean err() {
            return status != STATUS_OK;
        }
    
        // to initia variable
        public void init() {
            status = STATUS_OK;
            frameCount = 0;
            frames = new Vector<GifFrame>();
            gct = null;
            lct = null;
        }
    
        protected int read() {
            int curByte = 0;
            try {
                curByte = in.read();
            } catch (Exception e) {
                status = STATUS_FORMAT_ERROR;
            }
            return curByte;
        }
    
        protected int readBlock() {
            blockSize = read();
            int n = 0;
            if (blockSize > 0) {
                try {
                    int count = 0;
                    while (n < blockSize) {
                        count = in.read(block, n, blockSize - n);
                        if (count == -1) {
                            break;
                        }
                        n += count;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (n < blockSize) {
                    status = STATUS_FORMAT_ERROR;
                }
            }
            return n;
        }
    
        // Global Color Table
        protected int[] readColorTable(int ncolors) {
            int nbytes = 3 * ncolors;
            int[] tab = null;
            byte[] c = new byte[nbytes];
            int n = 0;
            try {
                n = in.read(c);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (n < nbytes) {
                status = STATUS_FORMAT_ERROR;
            } else {
                tab = new int[256]; // max size to avoid bounds checks
                int i = 0;
                int j = 0;
                while (i < ncolors) {
                    int r = ((int) c[j++]) & 0xff;
                    int g = ((int) c[j++]) & 0xff;
                    int b = ((int) c[j++]) & 0xff;
                    tab[i++] = 0xff000000 | (r << 16) | (g << 8) | b;
                }
            }
            return tab;
        }
    
        // Image Descriptor
        protected void readContents() {
            // read GIF file content blocks
            boolean done = false;
            while (!(done || err())) {
                int code = read();
                switch (code) {
                case 0x2C: // image separator
                    readImage();
                    break;
                case 0x21: // extension
                    code = read();
                    switch (code) {
                    case 0xf9: // graphics control extension
                        readGraphicControlExt();
                        break;
    
                    case 0xff: // application extension
                        readBlock();
                        String app = "";
                        for (int i = 0; i < 11; i++) {
                            app += (char) block[i];
                        }
                        if (app.equals("NETSCAPE2.0")) {
                            readNetscapeExt();
                        } else {
                            skip(); // don't care
                        }
                        break;
                    default: // uninteresting extension
                        skip();
                    }
                    break;
    
                case 0x3b: // terminator
                    done = true;
                    break;
    
                case 0x00: // bad byte, but keep going and see what happens
                    break;
                default:
                    status = STATUS_FORMAT_ERROR;
                }
            }
        }
    
        protected void readGraphicControlExt() {
            read(); // block size
            int packed = read(); // packed fields
            dispose = (packed & 0x1c) >> 2; // disposal method
            if (dispose == 0) {
                dispose = 1; // elect to keep old image if discretionary
            }
            transparency = (packed & 1) != 0;
            delay = readShort() * 10; // delay in milliseconds
            transIndex = read(); // transparent color index
            read(); // block terminator
        }
    
        // to get Stream - Head
        protected void readHeader() {
            String id = "";
            for (int i = 0; i < 6; i++) {
                id += (char) read();
            }
            if (!id.startsWith("GIF")) {
                status = STATUS_FORMAT_ERROR;
                return;
            }
            readLSD();
            if (gctFlag && !err()) {
                gct = readColorTable(gctSize);
                bgColor = gct[bgIndex];
            }
        }
    
        protected void readImage() {
            // offset of X
            ix = readShort(); // (sub)image position & size
            // offset of Y
            iy = readShort();
            // width of bitmap
            iw = readShort();
            // height of bitmap
            ih = readShort();
    
            // Local Color Table Flag
            int packed = read();
            lctFlag = (packed & 0x80) != 0; // 1 - local color table flag
    
            // Interlace Flag, to array with interwoven if ENABLE, with order
            // otherwise
            interlace = (packed & 0x40) != 0; // 2 - interlace flag
            // 3 - sort flag
            // 4-5 - reserved
            lctSize = 2 << (packed & 7); // 6-8 - local color table size
            if (lctFlag) {
                lct = readColorTable(lctSize); // read table
                act = lct; // make local table active
            } else {
                act = gct; // make global table active
                if (bgIndex == transIndex) {
                    bgColor = 0;
                }
            }
            int save = 0;
            if (transparency) {
                save = act[transIndex];
                act[transIndex] = 0; // set transparent color if specified
            }
            if (act == null) {
                status = STATUS_FORMAT_ERROR; // no color table defined
            }
            if (err()) {
                return;
            }
            decodeImageData(); // decode pixel data
            skip();
            if (err()) {
                return;
            }
            frameCount++;
            // create new image to receive frame data
            image = Bitmap.createBitmap(width, height, Config.RGB_565);
            // createImage(width, height);
            setPixels(); // transfer pixel data to image
            frames.addElement(new GifFrame(image, delay)); // add image to frame
            // list
            if (transparency) {
                act[transIndex] = save;
            }
            resetFrame();
        }
    
        // Logical Screen Descriptor
        protected void readLSD() {
            // logical screen size
            width = readShort();
            height = readShort();
            // packed fields
            int packed = read();
            gctFlag = (packed & 0x80) != 0; // 1 : global color table flag
            // 2-4 : color resolution
            // 5 : gct sort flag
            gctSize = 2 << (packed & 7); // 6-8 : gct size
            bgIndex = read(); // background color index
            pixelAspect = read(); // pixel aspect ratio
        }
    
        protected void readNetscapeExt() {
            do {
                readBlock();
                if (block[0] == 1) {
                    // loop count sub-block
                    int b1 = ((int) block[1]) & 0xff;
                    int b2 = ((int) block[2]) & 0xff;
                    loopCount = (b2 << 8) | b1;
                }
            } while ((blockSize > 0) && !err());
        }
    
        // read 8 bit data
        protected int readShort() {
            // read 16-bit value, LSB first
            return read() | (read() << 8);
        }
    
        protected void resetFrame() {
            lastDispose = dispose;
            lrx = ix;
            lry = iy;
            lrw = iw;
            lrh = ih;
            lastImage = image;
            lastBgColor = bgColor;
            dispose = 0;
            transparency = false;
            delay = 0;
            lct = null;
        }
    
        /**
         * Skips variable length blocks up to and including next zero length block.
         */
        protected void skip() {
            do {
                readBlock();
            } while ((blockSize > 0) && !err());
        }
    }

      该类中用到的几个基本方法是:

          read(InputStream Is)    读取gif图片流,注意只能是Gif!  具体调用方法参考下面的MyTextView.java类

          getImage();    获取第一帧图片;

          nextBitmap()   获取下一帧图片;

          getFrameCount();   获取分解后的总帧数;

          nextDelay()     获取帧与帧之间的时间间隔,用于在线程中控制播放效果

    对于这个类还想说两句的是不建议把它搞得明明白白,我们的目的是利用一些工具做出想要的控件。当然如果你想做一个制作Gif的应用那反而要好好研究一下算法了。

      下面给出来利用GifOpenHelper类设计的TextView升级版本,这个TextView在原有功能的基础上还可以实现静态图片显示、动态图片显示,以及动态图片、静态图片和文字混合显示。 这个类是我自己写的,所以注释给的比较全面~

    package com.example.android_qqfix;
    
    import java.util.ArrayList;
    
    import java.util.HashMap;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    import com.example.utils.FaceData;
    
    import android.content.Context;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.os.Handler;
    import android.text.Spannable;
    import android.text.SpannableString;
    import android.text.style.ImageSpan;
    import android.util.AttributeSet;
    import android.widget.TextView;
    
    public class MyTextView extends TextView{
    
    
        /**
         * @author Dragon
         * SpanInfo 类用于存储一个要显示的图片(动态或静态)的信息,包括分解后的每一帧mapList、替代文字的起始位置、终止位置
         * 、帧的总数、当前需要显示的帧、帧与帧之间的时间间隔 
         */
        private class SpanInfo{
            ArrayList<Bitmap> mapList;
            int start,end,frameCount,currentFrameIndex,delay;
            public SpanInfo(){
                mapList=new ArrayList<Bitmap>();
                start=end=frameCount=currentFrameIndex=delay=0;    
            }
        }
        
        /**
         * spanInfoList 是一个SpanInfo的list ,用于处理一个TextView中出现多个要匹配的图片的情况
         */
        private ArrayList<SpanInfo> spanInfoList=null;
        private Handler handler;           //用于处理从子线程TextView传来的消息
        private String myText;             //存储textView应该显示的文本
        
        /**
         * 这三个构造方法一个也不要少,否则会产生CastException,注意在这三个构造函数中都为spanInfoList实例化,可能有些浪费
         * ,但保证不会有空指针异常
         * @param context
         * @param attrs
         * @param defStyle
         */
        public MyTextView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            // TODO Auto-generated constructor stub
            spanInfoList=new ArrayList<SpanInfo>();
        }
    
        public MyTextView(Context context, AttributeSet attrs) {
            super(context, attrs);
            // TODO Auto-generated constructor stub
            spanInfoList=new ArrayList<SpanInfo>();
        }
    
        public MyTextView(Context context) {
            super(context);
            // TODO Auto-generated constructor stub
            spanInfoList=new ArrayList<SpanInfo>();
        }
        
        
        
        /**
         * 对要显示在textView上的文本进行解析,看看是否文本中有需要与Gif或者静态图片匹配的文本
         * 若有,那么调用parseGif 对该文本对应的Gif图片进行解析 或者嗲用parseBmp解析静态图片
         * @param inputStr
         */
        private void parseText(String inputStr){
            myText=inputStr;
            Pattern mPattern=Pattern.compile("\\..");
            Matcher mMatcher=mPattern.matcher(inputStr);
            while(mMatcher.find()){
                String faceName=mMatcher.group();
                Integer faceId=null;
                /**
                 * 这里匹配时用到了图片库,即一个专门存放图片id和其匹配的名称的静态对象,这两个静态对象放在了FaceData.java
                 * 中,并采用了静态块的方法进行了初始化,不会有空指针异常
                 */
                
                if((faceId=FaceData.gifFaceInfo.get(faceName))!=null){
                    parseGif(faceId, mMatcher.start(), mMatcher.end());
                }
                else if((faceId=FaceData.staticFaceInfo.get(faceName))!=null){
                    parseBmp(faceId, mMatcher.start(), mMatcher.end());
                }
                
            }
            
            
        }
        
        /**
         * 对静态图片进行解析:
         * 创建一个SpanInfo对象,帧数设为1,按照下面的参数设置,最后不要忘记将SpanInfo对象添加进spanInfoList中,
         * 否则不会显示
         * @param resourceId
         * @param start
         * @param end
         */
        private void parseBmp(int resourceId,int start, int end){
            Bitmap bitmap=BitmapFactory.decodeResource(getContext().getResources(), resourceId);
            ImageSpan imageSpan=new ImageSpan(getContext(),bitmap);
            SpanInfo spanInfo=new SpanInfo();
            spanInfo.currentFrameIndex=0;
            spanInfo.frameCount=1;
            spanInfo.start=start;
            spanInfo.end=end;
            spanInfo.delay=100;
            spanInfo.mapList.add(bitmap);
            spanInfoList.add(spanInfo);
            
        }
        
        /**
         * 解析Gif图片,与静态图片唯一的不同是这里需要调用GifOpenHelper类读取Gif返回一系一组bitmap(用for 循环把这一
         * 组的bitmap存储在SpanInfo.mapList中,此时的frameCount参数也大于1了)
         * @param resourceId
         * @param start
         * @param end
         */
        private void parseGif(int resourceId ,int start, int end){   
        
            GifOpenHelper helper=new GifOpenHelper();
            helper.read(getContext().getResources().openRawResource(resourceId));
            SpanInfo spanInfo=new SpanInfo();
            spanInfo.currentFrameIndex=0;
            spanInfo.frameCount=helper.getFrameCount();
            spanInfo.start=start;
            spanInfo.end=end;
            spanInfo.mapList.add(helper.getImage());
            for(int i=1; i<helper.getFrameCount(); i++){
                spanInfo.mapList.add(helper.nextBitmap());
            }
            spanInfo.delay=helper.nextDelay();        //获得每一帧之间的延迟
            spanInfoList.add(spanInfo);
    
        }
        
        /**
         * MyTextView 与外部对象的接口,以后设置文本内容时使用setSpanText() 而不再是setText();
         * @param handler
         * @param text
         */
        public void setSpanText(Handler handler, String text){
            this.handler=handler;      //获得UI的Handler
            parseText(text);           //对String对象进行解析
            TextRunnable r=new TextRunnable();   //生成Runnable对象
            handler.post(r);       //利用UI线程的Handler 将r添加进消息队列中。
            
        }
        
        
        public class TextRunnable implements Runnable{
    
            @Override
            public void run() {
                // TODO Auto-generated method stub
                SpannableString sb=new SpannableString(""+myText);   //获得要显示的文本
                int gifCount=0;
                SpanInfo info=null;
                for(int i=0; i<spanInfoList.size(); i++){  //for循环,处理显示多个图片的问题
                    info=spanInfoList.get(i);
                    if(info.mapList.size()>1){       
                        /*
                         * gifCount用来区分是Gif还是BMP,若是gif gifCount>0 ,否则gifCount=0
                         */
                        gifCount++;
                        
                    }
                    Bitmap bitmap=info.mapList.get(info.currentFrameIndex);
                    info.currentFrameIndex=(info.currentFrameIndex+1)%(info.frameCount);
                    /**
                     * currentFrameIndex 用于控制当前应该显示的帧的序号,每次显示之后currentFrameIndex
                     * 应该加1 ,加到frameCount后再变成0循环显示
                     */
                    
                    if(gifCount!=0){
                        bitmap=Bitmap.createScaledBitmap(bitmap, 60, 60, true);
                    
                    }
                    else{
                        bitmap=Bitmap.createScaledBitmap(bitmap, 30, 30, true);
                    }
                    ImageSpan imageSpan=new ImageSpan(getContext(),bitmap);   
                    sb.setSpan(imageSpan, info.start, info.end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    
                }
                //对所有的图片对应的ImageSpan完成设置后,调用TextView的setText方法设置文本
                MyTextView.this.setText(sb);  
                
                /**
                 * 这一步是为了节省内存而是用,即如果文本中只有静态图片没有动态图片,那么该线程就此终止,不会重复执行
                 * 。而如果有动图,那么会一直执行
                 */
                if(gifCount!=0){
                    handler.postDelayed(this,info.delay );
                
                }
                
            }
            
        }
        
        
    
    }


     

    这里有几点要特别说明:

    1、不能在MyTextView中开辟子线程,然后利用sleep方法每隔一段时间像ChatActivity的Handler发送一个Message, 这样的话系统也认为是线程不安全的,会报错。经过我尝试,目前可行的办法,就是在MyTextView中创建一个Runnable对象,然后用UI的Handler的post() 和postDelay() 方法按照一定的时间间隔调用。至于其原因我也不太明白,但这说明采用Runnable对象比采用Message对象的线程安全性更高一些。

    2、还有一点是为什么创建这个类?因为在QQ聊天ListView中有多个TextView,几乎不可能在UI线程中获得每一个TextView的引用然后同步控制它们所显示的图片,因此只能把这个操作放给每一个TextView自己去执行相关的操作,这样的代码写出来比较简洁,最大的一个好处就是可复用性好,并且接口调用十分简单:只需要setSpanText(Handler handler, String text);即可,后面会有说明。

      此外上面已经提到,这里对表情数据的组织方式进行了优化,新建了一个类用于存储静态对象,并且采用了静态块完成初始化:

    package com.example.utils;
    
    import java.util.HashMap;
    
    
    import com.example.android_qqfix.R;
    
    public class FaceData {
        public static HashMap<String, Integer> gifFaceInfo;
        public static HashMap<String,Integer> staticFaceInfo;
        public static String[] gifFaceName={"\ji","\gl"};
        public static Integer[] gifFaceId={R.raw.ji,R.raw.gl};
        public static int[] faceId={R.drawable.f_static_000,R.drawable.f_static_001,R.drawable.f_static_002,R.drawable.f_static_003
                ,R.drawable.f_static_004,R.drawable.f_static_005,R.drawable.f_static_006,R.drawable.f_static_009,R.drawable.f_static_010,R.drawable.f_static_011
                ,R.drawable.f_static_012,R.drawable.f_static_013,R.drawable.f_static_014,R.drawable.f_static_015,R.drawable.f_static_017,R.drawable.f_static_018};
        public static String[] faceName={"\呲牙","\淘气","\流汗","\偷笑","\再见","\敲打","\擦汗","\流泪","\掉泪","\小声","\炫酷","\发狂"
                 ,"\委屈","\便便","\菜刀","\微笑","\色色","\害羞"};
        
        //静态块的使用
        static {
            gifFaceInfo=new HashMap<String,Integer>();
            staticFaceInfo=new HashMap<String,Integer>();
            for(int i=0;i<gifFaceName.length;i++){
                gifFaceInfo.put(gifFaceName[i], gifFaceId[i]);
            }
            for(int i=0;i<faceId.length;i++){
                staticFaceInfo.put(faceName[i], faceId[i]);
            }
        }
        
    
    }

    如果有需要的话,可以再添加几个静态方法用于对表情数据进行修改,这里不再赘述。

      以上三个类(MyTextView,GifOpenHelper, FaceData)配合起来使用,就可以构成一个比较独立的自定义TextView, 具有显示图片的功能,并且不需要在外部使用SpannableString 的方法设置,因为MyTextView内部已经封装好了,下面那QQ ChatActivity的代码做一个对比:

    这是不使用自定义MyTextView之前需要显示图片进行的操作:

       

     private void setFaceText(TextView textView,String text){
            SpannableString spanStr=parseString(text);
            textView.setText(spanStr);
        }
       
        
        private void setFace(SpannableStringBuilder spb, String faceName){
            Integer faceId=faceMap.get(faceName);
            if(faceId!=null){
                Bitmap bitmap=BitmapFactory.decodeResource(getResources(), faceId);
                bitmap=Bitmap.createScaledBitmap(bitmap, 30, 30, true);
                ImageSpan imageSpan=new ImageSpan(this,bitmap);
                SpannableString spanStr=new SpannableString(faceName);
                spanStr.setSpan(imageSpan, 0, faceName.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                spb.append(spanStr);    
            }
            else{
                spb.append(faceName);
            }
            
        }
        private SpannableString parseString(String inputStr){
            SpannableStringBuilder spb=new SpannableStringBuilder();
            Pattern mPattern= Pattern.compile("\\..");
            Matcher mMatcher=mPattern.matcher(inputStr);
            String tempStr=inputStr;
            
            while(mMatcher.find()){
                int start=mMatcher.start();
                int end=mMatcher.end();
                spb.append(tempStr.substring(0,start));
                String faceName=mMatcher.group();
                setFace(spb, faceName);
                tempStr=tempStr.substring(end, tempStr.length());
                
                mMatcher.reset(tempStr);
            }
            spb.append(tempStr);
            return new SpannableString(spb);
        }
        
        
    
    
    
    //然后调用时
    setFaceText(holder.textView, chatList.get(position).get(from[1]).toString());

      而这是采用MyTextView封装之后的调用方法:

    holder.textView.setSpanText(handler,chatList.get(position).get(from[1]).toString());

    可见虽然设计MyTextView需要花点功夫,但是调用时换来极大的方便! 而且可以支持动态表情。

    另外注意一点如使用MyTextView 那么xml布局文件中需要做一些修改,就是把TextView 改成自己定义的TextView子类

    <com.example.android_qqfix.MyTextView 
            android:id="@+id/chatlist_text_me"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toLeftOf="@id/chatlist_image_me"
            android:layout_alignTop="@id/chatlist_image_me"
            android:textSize="8pt"
            android:background="@drawable/balloon_back_right"
            android:paddingTop="13dip"
            android:paddingBottom="18dip"      />

      以上就是本节的主要内容,痛痛快快的写一下博客心情很好~ 不过我想下次见面应该是暑假了,到时我可能会做一个类似FlappyBird之类的小游戏与大家共享,安卓有你更精彩!

      最后给自己的寄语:静心学习,努力奋斗,明天更灿烂!

    本讲源码地址,欢迎下载:http://vdisk.weibo.com/s/uu2pYkVAfiGo-

  • 相关阅读:
    实战练习6—水波纹制作
    实战练习5—冰块中的效果
    实战练习4—逼真眼泪
    5、选择工具&描边
    实战练习3-修饰服装皱褶
    实战练习2—方块
    实战练习1—照片的局部放大
    23、裁剪
    iOS 处理第三方SDK冲突问题
    iOS 修改启动图无效
  • 原文地址:https://www.cnblogs.com/carlos-vic/p/Carlos_V_Android_17.html
Copyright © 2011-2022 走看看