当前位置: 移动技术网 > 移动技术>移动开发>Android > android计算器简单实现代码

android计算器简单实现代码

2019年07月24日  | 移动技术网移动技术  | 我要评论

本文实例为大家分享了android计算器的具体实现代码,供大家参考,具体内容如下

这里写图片描述

这里写图片描述

java代码:

package com.itheima74.simplecalculator4;

import android.os.bundle;
import android.support.v7.app.appcompatactivity;
import android.view.menu;
import android.view.menuitem;
import android.view.view;
import android.widget.textview;
import android.widget.toast;

import com.iflytek.cloud.initlistener;
import com.iflytek.cloud.speechconstant;
import com.iflytek.cloud.speecherror;
import com.iflytek.cloud.speechsynthesizer;
import com.iflytek.cloud.speechutility;
import com.iflytek.cloud.synthesizerlistener;
import com.iflytek.cloud.util.resourceutil;

import java.util.arraylist;

/**
 * 简易计算器(第三版)
 * 功能介绍:
 * 1.支持连续计算
 * 2.支持离线语音
 * 3.科大讯飞在线(离线)语音合成sdk使用步骤:
 * a.下载sdk,注册appid
 * b.拷贝libs目录下msc.jar至工程libs目录,右键:add as library
 * c.创建assets目录,拷贝tts文件夹下3个离线发音人资源
 * d.创建jnilibs目录,拷贝armeabi文件夹,x86文件(视具体手机机型而定)
 * e.初始化sdk
 * f.初始化在线或离线语音
 * g.开始合成(朗读文字)
 */
public class mainactivity extends appcompatactivity implements view.onclicklistener {

  private textview tv;// 显示控件
  private arraylist<string> mlist;// 存储用户输入集合
  private double mresult;// 计算结果,当除数为0时,无法计算结果,默认为初始值0
  private boolean mflag = true;// 控制在线语音功能是否开启的变量,默认开启

  @override
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity_main);

    initsdk();
    initview();
    initlist();
  }

  /**
   * 2.初始化离线语音
   *
   * @param flag 离线语音开启或关闭开关
   * @param msg 要朗读的文字
   */
  private void initlocalhecheng(boolean flag, string msg) {
    if (flag) {
      //1.创建speechsynthesizer对象,第二个参数:本地合成传initlistener
      speechsynthesizer mtts = speechsynthesizer.createsynthesizer(this, new initlistener() {
        @override
        public void oninit(int code) {

        }
      });
      //2.合成参数设置
      //设置引擎类型为本地
      mtts.setparameter(speechconstant.engine_type, speechconstant.type_local);
      //设置本地发音人
      mtts.setparameter(speechconstant.voice_name, "xiaoyan");
      //加载本地合成资源,respath为本地合成资源路径
      mtts.setparameter(resourceutil.tts_res_path, getresourcepath());
      // 设置语速
      mtts.setparameter(speechconstant.speed, "60");
      // 设置音调
      mtts.setparameter(speechconstant.pitch, "50");
      // 设置音量
      mtts.setparameter(speechconstant.volume, "100");
      // 设置播放器音频流类型
      mtts.setparameter(speechconstant.stream_type, "3");
      //设置合成音频保存位置(可自定义保存位置),保存在“./sdcard/iflytek.pcm”
      //保存在sd卡需要在androidmanifest.xml添加写sd卡权限
      //如果不需要保存合成音频,注释该行代码
      //mtts.setparameter(speechconstant.tts_audio_path, "./sdcard/iflytek.pcm");
      //3.开始合成
      mtts.startspeaking(msg, msynlistener);
    }
  }

  // 获取发音人资源路径
  private string getresourcepath() {
    stringbuffer tempbuffer = new stringbuffer();
    // 合成通用资源
    tempbuffer.append(resourceutil.generateresourcepath(this, resourceutil.resource_type.assets, "tts/common.jet"));
    tempbuffer.append(";");
    // 发音人资源
    tempbuffer.append(resourceutil.generateresourcepath(this, resourceutil.resource_type.assets, "tts/xiaoyan.jet"));
    return tempbuffer.tostring();
  }

  /**
   * 1.初始化sdk
   */
  private void initsdk() {
    speechutility.createutility(this, speechconstant.appid + "=58ba4628");
  }

  // 创建一个选项菜单
  @override
  public boolean oncreateoptionsmenu(menu menu) {
    getmenuinflater().inflate(r.menu.main, menu);
    return true;
  }

  // 处理选项菜单的点击事件
  @override
  public boolean onoptionsitemselected(menuitem item) {
    switch (item.getitemid()) {
      case r.id.exit:
        this.finish();
        break;
      case r.id.open_local_voice:
        mflag = true;
        break;
      case r.id.close_local_voice:
        mflag = false;
        break;
    }
    return super.onoptionsitemselected(item);
  }


  /**
   * 2.在线语音合成,朗读
   *
   * @param flag 控制方法的执行,true:执行,false:不执行
   * @param msg 需要朗读的文字
   */
  /*private void inityuyinhecheng(boolean flag, string msg) {
    if (flag) {
      //1.创建speechsynthesizer对象, 第二个参数:本地合成时传initlistener
      speechsynthesizer mtts = speechsynthesizer.createsynthesizer(this, null);
      //2.合成参数设置,详见《科大讯飞msc api手册(android)》speechsynthesizer 类
      mtts.setparameter(speechconstant.voice_name, mvoicename);//设置发音人
      mtts.setparameter(speechconstant.speed, "50");//设置语速
      mtts.setparameter(speechconstant.volume, "80");//设置音量,范围0~100
      mtts.setparameter(speechconstant.engine_type, speechconstant.type_cloud); //设置云端
      //设置合成音频保存位置(可自定义保存位置),保存在“./sdcard/iflytek.pcm”
      //保存在sd卡需要在androidmanifest.xml添加写sd卡权限
      //如果不需要保存合成音频,注释该行代码
      //mtts.setparameter(speechconstant.tts_audio_path, "./sdcard/iflytek.pcm");
      //3.开始合成
      mtts.startspeaking(msg, msynlistener);
    }

  }*/

  // 合成监听器
  private synthesizerlistener msynlistener = new synthesizerlistener() {
    //开始播放
    @override
    public void onspeakbegin() {

    }

    //缓冲进度回调
    //percent为缓冲进度0~100,beginpos为缓冲音频在文本中开始位置,endpos表示缓冲音频在文本中结束位置,
    //info为附加信息。
    @override
    public void onbufferprogress(int i, int i1, int i2, string s) {

    }

    // 暂停播放
    @override
    public void onspeakpaused() {

    }

    //恢复播放回调接口
    @override
    public void onspeakresumed() {

    }

    //播放进度回调
    //percent为播放进度0~100,beginpos为播放音频在文本中开始位置,endpos表示播放音频在文本中结束位置.
    @override
    public void onspeakprogress(int i, int i1, int i2) {

    }

    //会话结束回调接口,没有错误时,error为null
    @override
    public void oncompleted(speecherror speecherror) {

    }

    //会话事件回调接口
    @override
    public void onevent(int i, int i1, int i2, bundle bundle) {

    }
  };


  /**
   * 当集合中元素等于3项则开始计算
   */
  private void calculate() {
    double number1 = double.parsedouble(mlist.get(0));
    if (mlist.size() == 3) {
      double number2 = double.parsedouble(mlist.get(2));
      switch (mlist.get(1)) {
        case "+":
          mresult = number1 + number2;
          break;
        case "-":
          mresult = number1 - number2;
          break;
        case "*":
          mresult = number1 * number2;
          break;
        case "/":
          if (number2 == 0) {
            toast.maketext(this, "除数不能为0", toast.length_short).show();
          } else {
            mresult = number1 / number2;
          }
          break;
      }
      // 集合清空
      mlist.clear();
      mlist.add(string.valueof(mresult));
    } else {// 解决5=0的情况,5+=的情况
      mresult = number1;
    }
  }

  /**
   * 初始化集合
   */
  private void initlist() {
    mlist = new arraylist<>();
  }

  /**
   * 初始化控件,设置点击事件
   */
  private void initview() {
    tv = (textview) findviewbyid(r.id.tv);
    findviewbyid(r.id.bt_0).setonclicklistener(this);
    findviewbyid(r.id.bt_1).setonclicklistener(this);
    findviewbyid(r.id.bt_2).setonclicklistener(this);
    findviewbyid(r.id.bt_3).setonclicklistener(this);
    findviewbyid(r.id.bt_4).setonclicklistener(this);
    findviewbyid(r.id.bt_5).setonclicklistener(this);
    findviewbyid(r.id.bt_6).setonclicklistener(this);
    findviewbyid(r.id.bt_7).setonclicklistener(this);
    findviewbyid(r.id.bt_8).setonclicklistener(this);
    findviewbyid(r.id.bt_9).setonclicklistener(this);
    findviewbyid(r.id.bt_add).setonclicklistener(this);
    findviewbyid(r.id.bt_sub).setonclicklistener(this);
    findviewbyid(r.id.bt_mul).setonclicklistener(this);
    findviewbyid(r.id.bt_div).setonclicklistener(this);
    findviewbyid(r.id.bt_dot).setonclicklistener(this);
    findviewbyid(r.id.bt_equal).setonclicklistener(this);
    findviewbyid(r.id.bt_clear).setonclicklistener(this);
  }

  // 设置按钮的点击事件
  @override
  public void onclick(view view) {
    // 每次按钮被点击,都获取文本框内容
    string number = tv.gettext().tostring();

    switch (view.getid()) {
      case r.id.bt_0:
        if (!number.equals("0")) {// 前面不为0,才能追加0
          tv.append("0");
        }
        initlocalhecheng(mflag, tv.gettext().tostring());
        break;
      case r.id.bt_1:
        if (number.equals("0")) {
          tv.settext("1");
        } else {
          tv.append("1");
        }
        initlocalhecheng(mflag, tv.gettext().tostring());
        break;
      case r.id.bt_2:
        if (number.equals("0")) {
          tv.settext("2");
        } else {
          tv.append("2");
        }
        initlocalhecheng(mflag, tv.gettext().tostring());
        break;
      case r.id.bt_3:
        if (number.equals("0")) {
          tv.settext("3");
        } else {
          tv.append("3");
        }
        initlocalhecheng(mflag, tv.gettext().tostring());
        break;
      case r.id.bt_4:
        if (number.equals("0")) {
          tv.settext("4");
        } else {
          tv.append("4");
        }
        initlocalhecheng(mflag, tv.gettext().tostring());
        break;
      case r.id.bt_5:
        if (number.equals("0")) {
          tv.settext("5");
        } else {
          tv.append("5");
        }
        initlocalhecheng(mflag, tv.gettext().tostring());
        break;
      case r.id.bt_6:
        if (number.equals("0")) {
          tv.settext("6");
        } else {
          tv.append("6");
        }
        initlocalhecheng(mflag, tv.gettext().tostring());
        break;
      case r.id.bt_7:
        if (number.equals("0")) {
          tv.settext("7");
        } else {
          tv.append("7");
        }
        initlocalhecheng(mflag, tv.gettext().tostring());
        break;
      case r.id.bt_8:
        if (number.equals("0")) {
          tv.settext("8");
        } else {
          tv.append("8");
        }
        initlocalhecheng(mflag, tv.gettext().tostring());
        break;
      case r.id.bt_9:
        if (number.equals("0")) {
          tv.settext("9");
        } else {
          tv.append("9");
        }
        initlocalhecheng(mflag, tv.gettext().tostring());
        break;
      case r.id.bt_add:
        // 语音朗读
        initlocalhecheng(mflag, "加");
        // 1.将当前屏幕上的数字保存到mlist
        mlist.add(number);
        // 2.判断是否满足3项并计算
        this.calculate();
        // 3.将"+"保存到mlist
        mlist.add("+");
        // 4.tv置0
        tv.settext("0");
        break;
      case r.id.bt_sub:
        // 语音朗读
        initlocalhecheng(mflag, "减");
        // 1.获取前屏幕上的数字保存到mlist
        mlist.add(number);
        // 2.判断是否满足3项并计算
        this.calculate();
        // 3.将"-"保存到mlist
        mlist.add("-");
        // 4.tv置0
        tv.settext("0");
        break;
      case r.id.bt_mul:
        // 语音朗读
        initlocalhecheng(mflag, "乘");
        // 1.获取前屏幕上的数字保存到mlist
        mlist.add(number);
        // 2.判断是否满足3项并计算
        this.calculate();
        // 3.将"*"保存到mlist
        mlist.add("*");
        // 4.tv置0
        tv.settext("0");
        break;
      case r.id.bt_div:
        // 语音朗读
        initlocalhecheng(mflag, "除");
        // 1.获取前屏幕上的数字保存到mlist
        mlist.add(number);
        // 2.判断是否满足3项并计算
        this.calculate();
        // 3.将"/"保存到mlist
        mlist.add("/");
        // 4.tv置0
        tv.settext("0");
        break;
      case r.id.bt_dot:
        // 1..53这种形式可以吗?xml默认显示0,clear时默认归0,则可解决这个问题
        // 2.0.53.5,显然,前面如有有了.,则不能再出现.
        if (!number.contains(".")) {// 前面不包含.才添加
          tv.append(".");
        }
        break;
      case r.id.bt_equal:
        // 1.获取前屏幕上的数字保存到mlist
        mlist.add(number);
        // 2.判断是否满足3项并计算
        this.calculate();
        // 3.tv显示结果
        tv.settext(string.valueof(mresult));
        // 4.朗读结果
        initlocalhecheng(mflag, "等于" + tv.gettext().tostring());
        // 5.清空集合
        mlist.clear();
        break;
      case r.id.bt_clear:
        // 语音朗读
        initlocalhecheng(mflag, "清除");

        tv.settext("0");
        mresult = 0;
        mlist.clear();
        break;
    }
  }

}

xml:

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:id="@+id/activity_main"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical"
  tools:context=".mainactivity">

  <textview
    android:id="@+id/tv"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="2"
    android:background="#000"
    android:gravity="center_vertical|end"
    android:maxlines="1"
    android:text="@string/text"
    android:textcolor="#fff"
    android:textsize="50sp" />

  <linearlayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:orientation="horizontal">

    <button
      android:id="@+id/bt_7"
      style="@style/button_style"
      android:text="@string/_7" />

    <button
      android:id="@+id/bt_8"
      style="@style/button_style"
      android:text="@string/_8" />

    <button
      android:id="@+id/bt_9"
      style="@style/button_style"
      android:text="@string/_9" />

    <button
      android:id="@+id/bt_div"
      style="@style/button_style"
      android:text="@string/div" />
  </linearlayout>

  <linearlayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:orientation="horizontal">

    <button
      android:id="@+id/bt_4"
      style="@style/button_style"
      android:text="@string/_4" />

    <button
      android:id="@+id/bt_5"
      style="@style/button_style"
      android:text="@string/_5" />

    <button
      android:id="@+id/bt_6"
      style="@style/button_style"
      android:text="@string/_6" />

    <button
      android:id="@+id/bt_mul"
      style="@style/button_style"
      android:text="@string/mul" />
  </linearlayout>

  <linearlayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:orientation="horizontal">

    <button
      android:id="@+id/bt_1"
      style="@style/button_style"
      android:text="@string/_1" />

    <button
      android:id="@+id/bt_2"
      style="@style/button_style"
      android:text="@string/_2" />

    <button
      android:id="@+id/bt_3"
      style="@style/button_style"
      android:text="@string/_3" />

    <button
      android:id="@+id/bt_sub"
      style="@style/button_style"
      android:text="@string/sub" />
  </linearlayout>

  <linearlayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:orientation="horizontal">

    <button
      android:id="@+id/bt_0"
      style="@style/button_style"
      android:text="@string/_0" />

    <button
      android:id="@+id/bt_dot"
      style="@style/button_style"
      android:text="@string/dot" />

    <button
      android:id="@+id/bt_equal"
      style="@style/button_style"
      android:text="@string/equal" />

    <button
      android:id="@+id/bt_add"
      style="@style/button_style"
      android:text="@string/add" />
  </linearlayout>

  <button
    android:id="@+id/bt_clear"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:text="@string/clear"
    android:textallcaps="false"
    android:textsize="25sp" />

</linearlayout>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网