Android计算器 Android实现简单加法计算器
叫我AC 人气:0package com.example.calculator; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends Activity { private TextView tv1; private EditText et1; private EditText et2; private Button btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv1 = (TextView) this.findViewById(R.id.textView1); et1 = (EditText) this.findViewById(R.id.editText1); et2 = (EditText) this.findViewById(R.id.editText2); btn = (Button) this.findViewById(R.id.button1); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String inputText1 = et1.getText().toString(); String inputText2 = et2.getText().toString(); int num1 = Integer.valueOf(inputText1).intValue(); int num2 = Integer.valueOf(inputText2).intValue(); num1 = num1+num2; inputText1 = String.valueOf(num1); tv1.setText(inputText1); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
小编再为大家分享安卓简单加法计算器的另一段实现代码:
界面上有两个输入框,默认值为0,一个文本输出框,一个按钮;输入数字后点击Button计算;
xml中输入框有个属性android:inputType=”number”记得注意下。
代码如下:
private EditText input1; private EditText input2; private TextView textView; int num = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); input1 = (EditText)findViewById(R.id.shurukuan); input2 = (EditText)findViewById(R.id.shurukuan2); textView = (TextView)findViewById(R.id.textView2); Button Btn1 = (Button)findViewById(R.id.button3); Btn1.setOnClickListener(new Button.OnClickListener(){ public void onClick(View v) { num= Integer.parseInt(input1.getText().toString()) + Integer.parseInt(input2.getText().toString()); textView.setText(Integer.toString(num)); } }); }
更多计算器功能实现,请点击专题: 计算器功能汇总 进行学习
加载全部内容