做手机应用很容易遇到这个需求,网上也有很多人实现了过程,这次刚好也遇到了,只在setThumb中添加了几句缩小按钮的代码以适应应用的需要,下面看一下实现效果吧:

      //在这里写点记事吧,就不新开了。这段时间一直忙于写android版的德州游戏,最初花了一周多点时间就出了一个粗略版应用,接下来大刀阔斧的把所有布局重新设计,大约改版了3-4次,主要是之前没有这方面经验,为了适应动画需求而做,终于在上周历时7-8天出了个动画版本。之前他们开会也确认德州android最终会交由北京开发,但我们还是继续保持,主要是为了做技术积累。
      星哥有天早上来了兴奋的给我说他终于想到要做什么了,把500wan小秘书改成app应用:1、节约短信成本;2、消息实时触达;3、内容多样化。恩,确实很好的一个设计,而且我也觉得我们有那个能力去实现。希望这个想法可以早日提上开发历程。
      那天看见有人在公司传阅这个博客,之前也出现过这样的事情,以前写过一些比较上火的文章,提到了很多人和事,最后不得不删除,前端时间还是想写一些,主要是为了记录走过的这些路,经历的这些点滴,所以在首页加了公司访问限制,对不住了。还是很想让看我博客的人知道不要传阅,看看娱乐还是可以的。
      好了,算是插了一段广告吧,时间有点晚了,贴完代码睡觉。

package com.esun.texas.view;
import android.content.Context;
import android.graphics.*;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AbsSeekBar;
import android.widget.SeekBar;
public class VerticalSeekbar extends SeekBar {
    private Drawable mThumb;
    private int height;
    private int width;
    public interface OnSeekBarChangeListener {
        void onProgressChanged(VerticalSeekbar VerticalSeekBar, int progress, boolean fromUser);
        void onStartTrackingTouch(VerticalSeekbar VerticalSeekBar);
        void onStopTrackingTouch(VerticalSeekbar VerticalSeekBar);
    }
    private OnSeekBarChangeListener mOnSeekBarChangeListener;
    public VerticalSeekbar(Context context) {
        this(context, null);
    }
    public VerticalSeekbar(Context context, AttributeSet attrs) {
        this(context, attrs, android.R.attr.seekBarStyle);
    }
    public VerticalSeekbar(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
    public void setOnSeekBarChangeListener(OnSeekBarChangeListener l) {
        mOnSeekBarChangeListener = l;
    }
    void onStartTrackingTouch() {
        if (mOnSeekBarChangeListener != null) {
            mOnSeekBarChangeListener.onStartTrackingTouch(this);
        }
    }
    void onStopTrackingTouch() {
        if (mOnSeekBarChangeListener != null) {
            mOnSeekBarChangeListener.onStopTrackingTouch(this);
        }
    }
    void onProgressRefresh(float scale, boolean fromUser) {
        Drawable thumb = mThumb;
        if (thumb != null) {
            setThumbPos(getHeight(), thumb, scale, Integer.MIN_VALUE);
            invalidate();
        }
        if (mOnSeekBarChangeListener != null) {
            mOnSeekBarChangeListener.onProgressChanged(this, getProgress(), fromUser);
        }
    }
    private void setThumbPos(int w, Drawable thumb, float scale, int gap) {
        int available = w+getPaddingLeft()-getPaddingRight();
        int thumbWidth = thumb.getIntrinsicWidth();
        int thumbHeight = thumb.getIntrinsicHeight();
        available -= thumbWidth;
        // The extra space for the thumb to move on the track
        available += getThumbOffset() * 2;
        int thumbPos = (int) (scale * available);
        int topBound, bottomBound;
        if (gap == Integer.MIN_VALUE) {
            Rect oldBounds = thumb.getBounds();
            topBound = oldBounds.top;
            bottomBound = oldBounds.bottom;
        } else {
            topBound = gap;
            bottomBound = gap + thumbHeight;
        }
        thumb.setBounds(thumbPos, topBound, thumbPos + thumbWidth, bottomBound);
    }
    protected void onDraw(Canvas c)
    {
        c.rotate(-90);
        c.translate(-height,0);
        super.onDraw(c);
    }
    protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
        height = View.MeasureSpec.getSize(heightMeasureSpec);
        width = View.MeasureSpec.getSize(widthMeasureSpec);
        this.setMeasuredDimension(width, height);
    }
    private Bitmap getThumbImage(Bitmap bmp, int width, int height){
        int w = bmp.getWidth(); int h = bmp.getHeight();
        Matrix m = new Matrix();
        m.postScale((float)width/w, (float)height/h);
        Log.d("test", "__"+w+"___"+h+"___"+width+"___"+height);
        return Bitmap.createBitmap(bmp, 0, 0, w, h, m, true);
    }
    @Override
    public void setThumb(Drawable thumb){
        Bitmap bmp = ((BitmapDrawable) thumb).getBitmap();
        int w = 25;
        int h = (int)(w*2.2766);
        bmp = getThumbImage(bmp, w, h);
        mThumb = new BitmapDrawable(bmp);
        super.setThumb(mThumb);
    }
    protected void onSizeChanged(int w, int h, int oldw, int oldh)
    {
        super.onSizeChanged(h, w, oldw, oldh);
    }
    public boolean onTouchEvent(MotionEvent event) {
        if (!isEnabled()) {
            return false;
        }
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                setPressed(true);
                onStartTrackingTouch();
                trackTouchEvent(event);
                break;
            case MotionEvent.ACTION_MOVE:
                trackTouchEvent(event);
                attemptClaimDrag();
                break;
            case MotionEvent.ACTION_UP:
                trackTouchEvent(event);
                onStopTrackingTouch();
                setPressed(false);
                break;
            case MotionEvent.ACTION_CANCEL:
                onStopTrackingTouch();
                setPressed(false);
                break;
        }
        return true;
    }
    private void trackTouchEvent(MotionEvent event) {
        final int Height = getHeight();
        final int available = Height - getPaddingBottom() - getPaddingTop();
        int Y = (int)event.getY();
        float scale;
        float progress = 0;
        if (Y > Height - getPaddingBottom()) {
            scale = 0.0f;
        } else if (Y  < getPaddingTop()) {
            scale = 1.0f;
        } else {
            scale = (float)(Height - getPaddingBottom()-Y) / (float)available;
        }
        final int max = getMax();
        progress = scale * max;
        setProgress((int) progress);
    }
    private void attemptClaimDrag() {
        if (getParent() != null) {
            getParent().requestDisallowInterceptTouchEvent(true);
        }
    }
    public boolean dispatchKeyEvent(KeyEvent event) {
        if(event.getAction()==KeyEvent.ACTION_DOWN)
        {
            KeyEvent newEvent = null;
            switch(event.getKeyCode())
            {
                case KeyEvent.KEYCODE_DPAD_UP:
                    newEvent = new KeyEvent(KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_DPAD_RIGHT);
                    break;
                case KeyEvent.KEYCODE_DPAD_DOWN:
                    newEvent = new KeyEvent(KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_DPAD_LEFT);
                    break;
                case KeyEvent.KEYCODE_DPAD_LEFT:
                    newEvent = new KeyEvent(KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_DPAD_DOWN);
                    break;
                case KeyEvent.KEYCODE_DPAD_RIGHT:
                    newEvent = new KeyEvent(KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_DPAD_UP);
                    break;
                default:
                    newEvent = new KeyEvent(KeyEvent.ACTION_DOWN,event.getKeyCode());
                    break;
            }
            return newEvent.dispatch(this);
        }
        return false;
    }
}
无标签信息 0 条

      项目需要加入声音,之前也写过一个小app,用了MediaPlayer,但是这次这个声音极其短,播放的时候没有反应只有一条日志,忘了内容了,大意就是内容太短,最后发现播放这类提示应应该是用SoundPool来播放,应用出来后,玩了一段时间发现没声音了,奇怪,什么意思,赶紧搜搜,下面这文章写的很不错:http://blog.sina.com.cn/s/blog_71d26ff00100uzci.html,把内容copy过来存档:
    SoundPool的用法就不再提了,网上资料多,就说说在实际应用中可能会遇到的一些奇葩的问题,这些问题应该是和底层实现上有关系。
1、AudioFlinger could not create track, status: -12
    SoundPool即音效池,在创建的时候 maxStream这个参数代表能够同时播放的最大音效数,这里切忌合理使用,写的太大后会报AudioFlinger could not create track, status: -12 。。。。一旦报了这个错,你就听不到声音了,呵呵。
2、256个音效
    当调用load方法的时候实际就是把音效加载到了 SoundPool中,此时返回的streamId其实就是该音效在SoundPool中的Id,这个ID从0还是1来着(有点记不清了)递增,不过要注意的是,不要超过 256 这个临界点。也就是说第257个声音加载进去后,调用play方法其实是播不出来的,说不定还会挤掉一些前面加载好的声音。这个256的限制通过查看SDK源码基本就能了解清楚,它底层就那么实现的,用一个类似堆栈来存。
3、unload方法和release方法
    如果你音效多,也不要指望unload方法来清除掉一些音效后再load新的进去,虽然unload后音效卸载了,但是前面分给它在SoundPool里面的Id可没有释放掉,也就是说这个时候你load新的进去只会在后面继续累加,然后累加多了就超过256了,然后就就听不到声音,然后就没有然后了。要想彻底清掉前面的音效请使用release方法,它会连内存中占用的资源一起释放掉。
其他还有点什么呢,load需要一点点时间,load后不要马上unload,load ---play--unload的做法并不可取,不要load太大的音效,它只会申请1M的内存空间。SoundPool出错后通常会看到retuen的值是0。

      最后我亲测了一次,发现果然是load值超过了256后就没有声音了,所以就用了一个HashMap把这个声音值存储了,结果发现还是解决不了问题,只能在值快到达200时主动release掉,release掉后要重新测试化播放器。下面把我的代码贴一下:

package com.esun.texas.controller;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.util.Log;
import com.esun.texas.R;
import com.esun.texas.config.Config;
import com.esun.texas.lib.Common;
import com.esun.texas.model.Mactivity;
import java.util.HashMap;
/**
 * Created by IntelliJ IDEA.
 * User: tuyl
 * Date: 12-4-1
 * Time: 下午4:15
 * To change this template use File | Settings | File Templates.
 */
public class Csound {
    public static MediaPlayer player = new MediaPlayer();
    public static SoundPool spool = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);
    public static AudioManager mgr = (AudioManager)Mactivity.NEW_ACTIVITY.getSystemService(Context.AUDIO_SERVICE);
    public static int CARD_SOUND = R.raw.card;
    public static int CHECK_SOUND = R.raw.check;
    public static int CHIPS_SOUND = R.raw.chips;
    public static int GATHER_CHIPS_SOUND = R.raw.chips_gathering;
    public static int FOLD_SOUND = R.raw.fold;
    public static int MY_TURN_SOUND = R.raw.myturn;
    public static int ONTURN_SOUND = R.raw.onturn;
    public static boolean isMute = false;
    public static HashMap sounds = new HashMap();
    private static int getSound(int resId){
        if(!sounds.containsKey(resId)){
            int spload = spool.load(Mactivity.NEW_ACTIVITY, resId, 1);
            sounds.put(resId, spload);
            Log.d(Config.LOG_TAG, "init sound:"+resId);
        }
        return sounds.get(resId);
    }
    /**
     * 播放短音效
     * @param resId
     */
    public static void play(int resId){
        try{
            if(isMute) return; //静音
            final int spload = spool.load(Mactivity.NEW_ACTIVITY, resId, 1);
            Log.d(Config.LOG_TAG, "play sound:"+resId+"___"+spload);
            spool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener(){
                public void onLoadComplete(android.media.SoundPool soundPool, int i, int i1){
                    try{
                        float streamVolumeCurrent=mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
                        float streamVolumeMax=mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
                        float volume=streamVolumeCurrent/streamVolumeMax;
                        spool.play(spload, volume, volume, 0, 0, 1);
                    }catch (Exception ex){
                        Common.errorReport("Csound.play.onLoadComplete", ex);
                    }
                }
            });
            if(spload > 200){
                spool.release();
                spool = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);
            }
        }catch (Exception ex){
            Common.errorReport("Csound.play", ex);
        }
    }
    public static void playMusic(int resSound){
        try{
            if(isMute) return; //静音
            Activity act = Mactivity.NEW_ACTIVITY;
            AssetFileDescriptor afd = act.getResources().openRawResourceFd(resSound);
            player.reset();
            player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
            player.prepare();
            player.start();
            afd.close();
            player.setOnCompletionListener(new MediaPlayer.OnCompletionListener(){
                public void onCompletion(MediaPlayer arg0){
                    player.release(); //释放资源
                }
            });
        }catch (Exception ex){
            Common.errorReport("Csound.playMusic", ex);
        }
    }
}
无标签信息 0 条
20 / 04 / 2012 buling

      刚开始写的时候就是直接从网上copy,因为像快速出原型,结果花费了好多时间做调试,代码离想象中总是差很远,最后我实在受不了了,只能自己一个字一个字的码出了一个类库,贴出来,分享给有用的人。使用方法:

RC4 rc4 = new RC4(Info.RC4_KEY);
String data = rc4..make("body");

这段代码我想解释都解释不了。

package com.esun.texas.lib;
public class RC4{
    public int[] box = new int[256];
    public RC4(String key){
        byte[] k = key.getBytes();
        int i = 0, x = 0, t = 0, l = k.length;
        for(i=0; i<256; i++){
            box[i] = i;
        }
        for(i=0; i<256; i++){
            x = (x+box[i]+k[i%l]) % 256;
            t = box[x];
            box[x] = box[i];
            box[i] = t;
        }
    }
    public byte[] make(byte[] data){
        int t, o, i=0, j = 0, l = data.length;
        byte[] out = new byte[l];
        int[] ibox = new int[256];
        System.arraycopy(box, 0, ibox, 0, 256);
        for(int c=0; c
            
无标签信息 0 条

      在玩家获胜后会出现星星环绕在用户头像周围,在写这个动画之前写过一个倒计时的效果,倒计时是重写了ImageView中使用不断重绘实现,这次使用了SurfaceView,关于surfaceview的组件网络已经有很多很专业的介绍了,这里就不重述了,看看效果图吧

      就是surfaceview刚被setVisibility后可能holder.lockCanvas()出现null,为了避免这个现象,我使用了一个thread一直重试,直到成功。好困就不解释了,下面直接贴源码了:

package com.esun.texas.utils;
import android.app.Activity;
import android.content.pm.ConfigurationInfo;
import android.graphics.*;
import android.os.Handler;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import com.esun.texas.R;
import com.esun.texas.config.Config;
import com.esun.texas.lib.Common;
import java.util.Timer;
import java.util.TimerTask;
/**
 * Created by IntelliJ IDEA.
 * User: tuyl
 * Date: 12-4-17
 * Time: 下午4:15
 * To change this template use File | Settings | File Templates.
 */
public class WinStarAnimation {
    public SurfaceView surface;
    public int num = 20;
    private SurfaceHolder holder;
    private Paint paint; //画笔
    private Bitmap star; //星星bitmap
    private Bitmap tmpBmp;
    private int[] starInfo; //星星信息
    private double [][] starsInfo = new double[num][2]; //星星缩放度、增减性 0->减, 1->增
    private int[][] pConfig = new int[num][2]; //星星坐标 [x, y]
    public int swidth, sheight;
    private Timer timer;
    private Canvas cas;
    private boolean isinit = false;
    private int runTime = 0;
    private int speed = 200;
    private Thread thread;
    private boolean isStop = true;
    public WinStarAnimation(SurfaceView surface, Bitmap star){
        this.surface = surface;
        this.surface.setZOrderOnTop(true);
        holder = this.surface.getHolder();
        holder.setFormat(PixelFormat.TRANSLUCENT); //设置透明
        holder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder surfaceHolder) {}
            @Override
            public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {}
            @Override
            public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
                _stopShow();
            }
        });
        paint = new Paint();
        this.star = star;
        starInfo = new int[]{star.getWidth(), star.getHeight()};
        swidth = 90; sheight = 110; //swidth = sur.getWidth(); sheight = sur.getHeight();
    }
    public WinStarAnimation setParams(int width, int height, int num){
        this.swidth = width;
        this.sheight = height;
        this.num = num;
        starsInfo = new double[num][2]; //星星缩放度、增减性 0->减, 1->增
        pConfig = new int[num][2];
        return this;
    }
    public Bitmap getNewStar(int index){
        tmpBmp = star.copy(Bitmap.Config.ARGB_8888, true);
        try{
            Matrix matrix = new Matrix();
            if(starsInfo[index][0]<0.2) {
                starsInfo[index][1] = 1;
            }else if(starsInfo[index][0] > 0.9){
                starsInfo[index][1] = 0;
            }
            if(starsInfo[index][1] > 0) starsInfo[index][0] += 0.1;
            else starsInfo[index][0] -= 0.1;
            matrix.postScale((float)starsInfo[index][0], (float)starsInfo[index][0]);
            tmpBmp = Bitmap.createBitmap(tmpBmp, 0, 0, starInfo[0], starInfo[1], matrix, true);
        }catch (Exception ex){
            Common.errorReport("WinStarAnimation.getNewStar", ex);
        }
        return tmpBmp;
    }
    private int initShow(){
        if(holder.isCreating()){ return 0;}
        if(isinit){ //已经初始化过了
            return 1;
        }
        int f = 0;
        try{
            cas = holder.lockCanvas();
            if(cas == null) return 0;
            Log.d(Config.LOG_TAG, "init win star animation...");
            Matrix matrix;
            for(int i=0; i3000){
                        Log.e(Config.LOG_TAG, "star win out time");
                        timer.cancel();
                        starHandle.sendEmptyMessage(0x001);
                    }
                    int f = initShow();
                    if(f>0){//初始化成功
                        Canvas cas = holder.lockCanvas(null);
                        if(cas != null){
                            cas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
                            for(int i=0; i
            
无标签信息 0 条

      一个好的应用应该是对用户做出的任何动作都做出响应,如当用户请求登陆请求时,应该弹出正在加载中的对话框让用户知道应用正在请求中,实现的方式是用Thread+ProgressDialog,通过Handler来通知加载完成。实现过程比较简单我就不多说了,先看效果图:

不描述,直接代码,代码是拼凑,主要是想说明过程。

public class LoginActivity extends Activity{
    public ProgressDialog loadingDialog;
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        loginThread("test", "test");
    }
    /**
    * 开始启动加载对话框
    */
    public void loading(Activity act){
        Log.d(Config.LOG_TAG, "Starting loading");
        loadingDialog = new ProgressDialog(act);
        loadingDialog.setTitle("正在加载数据...");
        loadingDialog.setMessage("请稍等...");
        loadingDialog.show();
    }
    /**
    * 结束加载对话框
    */
    public void stopLoading(){
        Log.d(Config.LOG_TAG, "Stop loading");
        if(loadingDialog != null){
            loadingDialog.dismiss();
        }
    }
    /**
    * 开始登陆检查线程
    */
    public void loginThread(final String uname, final String upwd){
        Common.loading(this); //开始加载
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                //get方式传密码是不好的做法
                String url = String.format("http://www.hcent.com/login/%s/%s", uname, upwd);
                String data = NetWork.getHttpData(url);
                //加载完成,发送消息
                Message msg = loadHandle.obtainMessage(StatusConfig.LOADING_OVER);
                Bundle bu = new Bundle();
                bu.putString("data", data);
                msg.setData(bu);
                loadHandle.sendMessage(msg);
            }
        });
        t.start();
    }
    /**
    * 消息通知句柄
    */
    public Handler loadHandle = new Handler(){
        @Override
        public void handleMessage(Message msg){
            if(msg.what == StatusConfig.LOADING_OVER){ //加载完成
                if(msg.getData().getString("data").equals("1")){ //登陆成功
                }
            }
            Common.stopLoading();
        }
    };
}
无标签信息 0 条

      前天下午(04/18)加了一会班导出了第一个比较完整的动画版德州扑克apk,昨天到今天打算把赛事界面整理一次,第一个遇到的问题就是切屏效果,先看效果图:

      看到的时候觉得应该很简单可以解决掉,但过程中遇到了两个难点问题:
      1、seekbar 中的thumb图标过大,网上很多资料说用minHeight、maxHeight两个字段可以解决,但是不知道是因为rp问题怎么都没有效果,算了,死心了我直接把图片大小改了(sorry,实在折腾不了了)。
      2、seekbar在切换中thumb图标需要改变,可以使用setThumb方法改变,但是不显示,google呗,问题找到了:
    看了下SeekBar父类AbsSeekBar的源码,发现setThumb仅仅是把AbsSeekBar的mThumb指向新的Drawable,并没有对新的Thumb的Bounds进行设定,但是在draw时,canvas要根据图像的bounds去画,这就出现了问题,输出了一下bounds的Log,发现新的Thumb的bounds的top和bottom都为0,也就是新Bar的高度为0, 这肯定是画不出来的。
解决方法:
在setThumb时,对新的Thumb Drawable设置它的Bounds,比如:
Rect oldbound = mOldThumbDrawable.getBounds();
int width = drawable.getIntrinsicWidth();
int height = drawable.getIntrinsicHeight();
int left = (oldbound.left + oldbound.right - width) / 2;
int top = (oldbound.top + oldbound.bottom - height) / 2;
Rect newbound = new Rect(left, top, left + width, top + height);
drawable.setBounds(newbound);
setThumb(drawable);

      这个来自博客:http://andynjux.blogbus.com/logs/60975275.html,问题是这哥们没有说mOldThumbDrawable怎么来的,也不知道是我傻了还是怎么的,一门心思的花时间去寻找一个方法返回thumbDrawable,好吧,几个小时都耗了,没效果,放弃,重写SeekBar一句代码搞定,重写SeekBar的setThumb方法,把thumbDrawable保存下来就好了:

    @Override
    public void setThumb(Drawable thumb){
        thumbDrawable = thumb;
        super.setThumb(thumb);
    }

      对于切屏有很多方法实现,本来想把网址贴出来,结果没有找到,到公司再补上吧,这里说一个最简单的方法android自带的
ViewFlipper,使用非常简单:


        
       

      对应控制切屏可以使用如下方法:

       ViewFlipper goldView = (ViewFlipper)findViewById(R.id.gold_cash_match_view);
       goldView.showNext(); //显示下一个view
       goldView.showPrevious(); //显示上一个view
       goldView.setDisplayedChild(index); //显示某一个view,指明序号

      解说到此,源码释放:

package com.esun.texas;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.*;
import com.esun.texas.config.Key;
import com.esun.texas.config.StatusConfig;
import com.esun.texas.config.UtilConfig;
import com.esun.texas.lib.Common;
import com.esun.texas.lib.NetWork;
import com.esun.texas.view.XSeekBar;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
/**
 * Created by IntelliJ IDEA.
 * User: tuyl
 * Date: 12-4-20
 * Time: 下午4:59
 * To change this template use File | Settings | File Templates.
 */
public class GoldActivity extends Activity {
    private int seekMax = 0;
    private int curIndex = 0;
    private XSeekBar xBar; //滑动条
    private ViewFlipper goldView;
    private int[] thumbs = new int[]{R.drawable.match_chuji_but, R.drawable.match_zhongji_but,
            R.drawable.match_gaoji_but, R.drawable.match_dashi_but};
    private int[] progs = new int[]{0, 65, 135, 200};
    private Intent tIntent; //启动赛桌
    String[] matchConf = new String[]{UtilConfig.MATCH_PRIMARY, UtilConfig.MATCH_MIDDLE,
            UtilConfig.MATCH_HIGH, UtilConfig.MATCH_SUPER};
    private JSONObject dataInfo = new JSONObject();
    /**
     * 初始化
     * @param savedInstanceState
     */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.match_gold);
        goldView = (ViewFlipper)findViewById(R.id.gold_cash_match_view);
        tIntent = new Intent(this, TableActivity.class);
        xBar = (XSeekBar)findViewById(R.id.match_switch_seekbar);
        seekMax = xBar.getMax();
        initSeekBar(); //初始化滑动条
    }
    private void showView(int index){
        ListView list = (ListView)goldView.getChildAt(index);
        if(!dataInfo.has(matchConf[index])){
            getGoldList(index); //获取赛桌信息
        }
        goldView.setDisplayedChild(index);
    }
    public Handler loadHandle = new Handler(){
        @Override
        public void handleMessage(Message msg){
            try{
                if(msg.what == StatusConfig.LOADING_OVER){ //加载完成
                    Common.stopLoading();
                }else if(msg.what == StatusConfig.GOLD_LIST_DATA){ //赛事加载完成
                    String data = msg.getData().getString("data");
                    int rank = msg.getData().getInt("rank");
                    JSONObject info = new JSONObject();
                    info.put("data", new JSONArray(data));
                    info.put("upTime", new Date().getTime());
                    dataInfo.put(matchConf[rank], info);
                    _showList(rank); //显示实现被忽略
                }
            }catch (Exception ex){
                Common.errorReport("GoldActivity.loadHandle", ex);
            }
        }
    };
    public void sendMessage(int what, int rank, String data){
        try{
            Message msg = loadHandle.obtainMessage(what);
            Bundle bu = new Bundle();
            bu.putInt("rank", rank);
            bu.putString("data", data);
            msg.setData(bu);
            loadHandle.sendMessage(msg);
        }catch (Exception ex){
            Common.errorReport("GoldActivity.sendMessage", ex);
        }
    }
    /**
     * 获取现金桌
     */
    public void getGoldList(final int rank){
        Common.loading(this); //启动线程开始加载
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                String data = "-----私有数据-----";
                sendMessage(StatusConfig.GOLD_LIST_DATA, rank, data);
                loadHandle.sendEmptyMessage(StatusConfig.LOADING_OVER);
            }
        });
        t.start();
    }
    /**
     * 初始化滑动条
     */
    public void initSeekBar(){
        xBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                int index = (int)i/(seekMax/thumbs.length+1);
                if(curIndex != index){
                    curIndex = index;
                    setThumb(xBar, index, i);
                    showView(index);
                }
            }
            private void setThumb(XSeekBar seekBar, int index, int prog){
                Drawable bdraw = getResources().getDrawable(thumbs[index]);
                Rect oldbound = seekBar.thumbDrawable.getBounds();
                int width = bdraw.getIntrinsicWidth();
                int height = bdraw.getIntrinsicHeight();
                int left = (oldbound.left + oldbound.right - width) / 2;
                int top = (oldbound.top + oldbound.bottom - height) / 2;
                Rect newbound = new Rect(left, top, left + width, top + height);
                bdraw.setBounds(newbound);
                seekBar.setThumb(bdraw);
                seekBar.setThumbOffset(0);
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int prog = seekBar.getProgress();
                int pprog = seekMax/thumbs.length;
                int index = (int)((float)prog/pprog);
                index = index >= thumbs.length ? thumbs.length-1 : index;
                seekBar.setProgress(progs[index]);
            }
        });
    }
}
无标签信息 0 条