【Android App】Calculator(二)计算过程详细分析

在上一片文章【Android App】Calculator(一)onCreate过程分析
摘要由CSDN通过智能技术生成

    在上一片文章【Android App】Calculator(一)onCreate过程分析中我们简单介绍了Calculator启动过程中都做了些什么事情,比如都历史记录,初始化应用界面等。。。在今天这篇文章我们将重点分析Calculator是如何实现计算用户输入的。

    为了能更好的分析这一过程,我输入的表达式选择了经典的海伦公式  S=√[p(p-a)(p-b)(p-c)] 这里的a=3,b=4,c=5,p=6(p=(a+b+c)/2 )。如下图:


    结果显而易见为6,那么好,我们现在就来分析Calculator的这一计算过程的实现。


   从输入开始

    还记得我们上一节讲了在onCreate方法中,界面上的每一个Button都会被注册监听事件 mListener,当我们按下第一个字符√时,代表√按钮的监听事件被触发,我们先来看一下对象mListener所属的类

EventListener

/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.app.calculator2;

import com.android.app.calculator2.R;

import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;

class EventListener implements View.OnKeyListener,
                               View.OnClickListener,
                               View.OnLongClickListener {
    Logic mHandler;
    ViewPager mPager;

    void setHandler(Logic handler, ViewPager pager) {
        mHandler = handler;
        mPager = pager;
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
        case R.id.del:
            mHandler.onDelete();
            break;

        case R.id.clear:
            mHandler.onClear();
            break;

        case R.id.equal:
            mHandler.onEnter();
            break;

        default:
            if (view instanceof Button) {
                String text = ((Button) view).getText().toString();
                if (text.length() >= 2) {
                    // add paren after sin, cos, ln, etc. from buttons
                    text += '(';
                }
                mHandler.insert(text);
                if (mPager != null && mPager.getCurrentItem() == Calculator.ADVANCED_PANEL) {
                    mPager.setCurrentItem(Calculator.BASIC_PANEL);
                }
            }
        }
    }

    @Override
    public boolean onLongClick(View view) {
        int id = view.getId();
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值