Quantcast
Channel: CSDN博客移动开发推荐文章
Viewing all articles
Browse latest Browse all 5930

Android开发-自定义View-AndroidStudio(二十五)数独(2)Handler延迟

$
0
0
转载请注明出处:http://blog.csdn.net/iwanghang/
觉得博文有用,请点赞,请评论,请关注,谢谢!~


老规矩,先上GIF动态图,看个效果,如果符合你的项目或者确定你要了解的内容,再往下看吧:

继续前面几篇博文。实现onDraw延迟效果,实现音效添加。稍后上传完整项目。



NewView.java:
package com.iwanghang.newview;

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

public class NewView extends View{
    // 单元格的宽度和高度
    private float width;
    private float height;

    private int checkPoint = 1; // 当前关卡

    private MainActivity mainActivity = (MainActivity) getContext();

    //private Number number = new Number();
    private Number number = new Number(checkPoint);

    public NewView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public NewView(MainActivity mainActivity) {
        super(mainActivity);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        this.width = w / 9f;
        this.height = h / 10f;
        super.onSizeChanged(w, h, oldw, oldh);
    }

    // 当Android系统需要绘制一个View对象时,就会调用该对象的onDraw
    @Override
    protected void onDraw(Canvas canvas) {
        System.out.println("AAA onDraw -----------------");
        // 画背景
        Paint backgroundPaint = new Paint();
        backgroundPaint.setColor(getResources().getColor(R.color.colorBackground));
        canvas.drawRect(0,0,getWidth(),getHeight(),backgroundPaint);

        Paint darkPaint = new Paint();
        darkPaint.setColor(getResources().getColor(R.color.colorDark));

        Paint hilitePaint = new Paint();
        hilitePaint.setColor(getResources().getColor(R.color.colorHilite));

        Paint lightPaint = new Paint();
        lightPaint.setColor(getResources().getColor(R.color.colorLight));

        // 绘制9X9的网络格
        // 两条距离为1的直线,视觉上会有割裂的效果
        for (int i = 0; i < 9; i++) {
            canvas.drawLine(0, i*height, getWidth(), i*height, lightPaint);
            canvas.drawLine(0, i*height+1, getWidth(), i*height+1, hilitePaint);
            canvas.drawLine(i*width, 0, i*width, getHeight(), lightPaint);
            canvas.drawLine(i*width+1, 0, i*width+1, getHeight(), hilitePaint);
        }

        // 绘制3X3的网络格
        for (int i = 0; i < 10; i++) {
            if (i % 3 != 0) {
                continue;
            }
            canvas.drawLine(0, i*height, getWidth(), i*height, darkPaint);
            canvas.drawLine(0, i*height+1, getWidth(), i*height+1, hilitePaint);
            canvas.drawLine(i*width, 0, i*width, getHeight(), darkPaint);
            //canvas.drawLine(i*width+1, 0, i*width+1, getHeight(), hilitePaint);
            canvas.drawLine(i*width, 1, i*width, getHeight(), hilitePaint);
        }

        // 绘制数字
        Paint numberPaint = new Paint();
        numberPaint.setColor(Color.BLACK);
        numberPaint.setStyle(Paint.Style.STROKE);
        numberPaint.setTextSize(height*0.75f);
        numberPaint.setTextAlign(Paint.Align.CENTER);
        numberPaint.setAntiAlias(true); // 抗锯齿

        /**
         * 数字居中位置
         * x轴居中比较容易计算
         * y轴居中的计算,依赖于FontMetrics,大家很容易百度到相关的知识
         */
        Paint.FontMetrics fm = numberPaint.getFontMetrics();
        float x = width / 2;
        float y = height / 2 - (fm.ascent + fm.descent) / 2;

//        canvas.drawText("1", 0 * width + x, 0 * height + y, numberPaint);
//        canvas.drawText("2", 1 * width + x, 1 * height + y, numberPaint);
//        canvas.drawText("3", 2 * width + x, 2 * height + y, numberPaint);
//        canvas.drawText("4", 3 * width + x, 3 * height + y, numberPaint);
//        canvas.drawText("5", 4 * width + x, 4 * height + y, numberPaint);

//        /**
//         * 根据Number类中的数组,绘制数字
//         */
//        for (int i = 0; i < 9; i++) {
//            for (int j = 0; j < 9; j++) {
//                canvas.drawText(number.getTileString(i,j), i*width+x, j*height+y, numberPaint);
//                mainActivity.playSound();
//                handler.sendEmptyMessageDelayed(0, 200); // 每次重绘后,等待200毫秒,给handler发消息
//            }
//        }

        /**
         * 绘制一个刷新文字
         */
        canvas.drawText("刷新",4*width+x,9*height+y,numberPaint);

        /**
         * 绘制关卡文字
         */
        Paint strPaint = new Paint();
        strPaint.setTextSize(height*0.5f);
        strPaint.setAntiAlias(true); // 抗锯齿
        canvas.drawText("第" + checkPoint + "关",6*width+x,9*height+y,strPaint);

        //super.onDraw(canvas);
//        canvas.drawText(number.getTileString(numberX,numberY), numberX*width+x, numberY*height+y, numberPaint);
//        System.out.println("numberY = " + numberY);
//        if (numberY < 9){
//            if (number.getTileString(numberX,numberY) != ""){
//                mainActivity.playSound();
//                handler.sendEmptyMessageDelayed(0, 200); // 每次重绘后,等待200毫秒,给handler发消息
//            }else {
//                handler.sendEmptyMessageDelayed(0, 0); // 每次重绘后,等待500毫秒,给handler发消息
//            }
//        }


        /**
         * 优先绘制上一次绘制过的数字
         */
        int numberIndexOld = 0;
        int ii = 0;
        int jj = 0;
        if (numberIndex != 0){ // 首次绘制,没有上一次绘制过的数字,所以不进入这个方法
            System.out.println("AAA 优先绘制上一次绘制过的数字 numberIndex = " + numberIndex);
            outterLoop1:
            for (int i = 0; i < 9; i++) {
                for (int j = 0; j < 9; j++) {
                    canvas.drawText(number.getTileString(i,j), i*width+x, j*height+y, numberPaint);
                    System.out.println("AAA 优先绘制上一次绘制过的数字 number = " + number.getTileString(i,j) + " | i = " + i
                            + " | j = " + j + " | numberIndexOld = " + numberIndexOld);
                    if (numberIndexOld == (numberIndex-1)){
                        ii = i;
                        jj = j;
                        break outterLoop1;
                    }
                    numberIndexOld = numberIndexOld + 1 ;
                }
            }
            jj = jj + 1;
            if (jj == 9){
                jj = 0;
                ii = ii + 1;
            }
        }

        int getOld = 0;
        /**
         * 根据Number类中的数组,绘制数字
         */
        System.out.println("AAA0 绘制数字 jj = " + jj + " | ii = " + ii);
        outterLoop2:
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                if (getOld == 0){ // 继续上一次绘制的数字的i和j,继续绘制
                    i = ii;
                    j = jj;
                    getOld = 1;
                }
                canvas.drawText(number.getTileString(i,j), i*width+x, j*height+y, numberPaint);
                numberIndex = numberIndex + 1 ;
                System.out.println("AAA0 绘制数字 number = " + number.getTileString(i,j) + " | i = " + i
                        + " | j = " + j);
                // 绘制过程中 遇到 不为空的数字 , 播放音效 并 延迟300毫秒
                System.out.println();
                if (number.getTileString(i,j) != "" && numberIndex<81){
                    mainActivity.playSound(); // 调用MainActivity里的方法,播放音效
                    handler.sendEmptyMessageDelayed(0, 300); // 等待300毫秒,给handler发消息
                    break outterLoop2;
                }
            }
        }



    }

    /**
     * 获取按下的数字
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        super.onTouchEvent(event);
        if (event.getAction() == MotionEvent.ACTION_DOWN){
            int selectedX = (int)(event.getX() / width);
            int selectedY = (int)(event.getY() / height);

            StringBuffer sb = new StringBuffer();

            if (selectedY < 9){
                int used[] = number.getUsedTilesByCoor(selectedX,selectedY);
                for (int i = 0; i < used.length; i++) {
                    sb.append(used[i]);
                }
                LayoutInflater layoutInflater = LayoutInflater.from(this.getContext());
                View layoutView = layoutInflater.inflate(R.layout.dialog,null);
                TextView textView = (TextView) layoutView.findViewById(R.id.usedTextId);
                textView.setText("该位置不可用数字 = " + sb.toString());
                AlertDialog.Builder builder = new AlertDialog.Builder(this.getContext());
                builder.setView(layoutView);
                AlertDialog dialog = builder.create();
                dialog.show();
            }

            //Toast.makeText(getContext(), "ACTION_DOWN = " + used, Toast.LENGTH_SHORT).show();
            if (selectedY == 9){
                if (selectedX>=3 && selectedX<=5){
                    //Toast.makeText(getContext(), "ACTION_DOWN = 刷新",Toast.LENGTH_SHORT).show();
                    if (checkPoint == 1){
                        checkPoint = 2;
                    } else if (checkPoint == 2){
                        checkPoint = 1;
                    }
                    //Toast.makeText(getContext(), "checkPoint = " + checkPoint, Toast.LENGTH_SHORT).show();
                    number = new Number(checkPoint);
                    numberIndex = 0;
                    invalidate(); // onDraw()
                }
            }

        }
        return true;
    }

    private int numberIndex = 0; // 绘制完成的数字,下标81
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            invalidate(); // onDraw();
        }
    };

}
MainActivity.java:
package com.iwanghang.newview;

import android.media.AudioManager;
import android.media.SoundPool;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    private SoundPool soundPool;
    private static int soundId;
    int resId = R.raw.doo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().hide();
        //setContentView(R.layout.activity_main);

        NewView newView = new NewView(this);

        setContentView(newView);
        initSoundPool(resId);
    }

    public void initSoundPool(int resId) { // 初始化声音池
        soundPool = new SoundPool(
                3, // maxStreams参数,该参数为设置同时能够播放多少音效
                AudioManager.STREAM_MUSIC, // streamType参数,该参数设置音频类型,在游戏中通常设置为:STREAM_MUSIC
                1 // srcQuality参数,该参数设置音频文件的质量,目前还没有效果,设置为0为默认值。
        );
        soundId = soundPool.load(this, resId, 1);
    }

    public void playSound() { // 播放声音,参数sound是播放音效的id,参数number是播放音效的次数
        soundPool.play(
                soundId, // 播放的音乐id
                1, // 左声道音量
                1, // 右声道音量
                1, // 优先级,0为最低
                0, // 循环次数,0无不循环,-1无永远循环
                1 // 回放速度 ,该值在0.5-2.0之间,1为正常速度
        );
    }

    public void stopSound() { // 播放声音,参数sound是播放音效的id,参数number是播放音效的次数
        if (soundPool != null && soundId > 0) {
            soundPool.stop(soundId);
            soundPool.release();
        }
    }

}


转载请注明出处:http://blog.csdn.net/iwanghang/



欢迎移动开发爱好者交流
沈阳或周边城市公司有意开发Android,请与我联系
联系方式

微信:iwanghang
QQ:413711276
邮箱:iwanghang@qq.com



觉得博文有用,请点赞,请评论,请关注,谢谢!~

作者:iwanghang 发表于2017/1/6 15:14:14 原文链接
阅读:39 评论:0 查看评论

Viewing all articles
Browse latest Browse all 5930

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>