在上一片文章【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();