本文实例为大家分享了Android实现两个数相加的具体代码,供大家参考,具体内容如下
要实现如图所示的加法计算器的话,还是比较简单的,下面直接上演示,有不懂的可以留言交流。
1、下面是activity.xml的布局文件
& lt; & # 63; xml version=" 1.0 " encoding=" utf - 8 " & # 63;比; & lt; LinearLayout xmlns: android=" http://schemas.android.com/apk/res/android " xmlns:工具=" http://schemas.android.com/tools " android: layout_width=" match_parent " android: layout_height=" match_parent " android:取向=按怪薄? 工具:上下文=?MainActivity”比; LinearLayout & lt; android: layout_width=" match_parent " android: layout_height=皐rap_content”比; & lt; TextView android: layout_width=" wrap_content " android: layout_height=" wrap_content " android:文本="请输入整数x:“/比; EditText & lt; android: id=癅 + id/edit1” android: layout_width=" wrap_content " android: layout_height=" wrap_content " android: layout_marginLeft=" 20 dp” android: ems=" 20 "/比; & lt;/LinearLayout> LinearLayout & lt; android: layout_width=" match_parent " android: layout_height=皐rap_content”比; & lt; TextView android: layout_width=" wrap_content " android: layout_height=" wrap_content " android:文本="请输入整数y:“/比; EditText & lt; android: id=癅 + id/edit2” android: layout_width=" wrap_content " android: layout_height=" wrap_content " android: layout_marginLeft=" 20 dp” android: ems=" 20 "/比; & lt;/LinearLayout> & lt;按钮 android: id=癅 + id/btn” android: layout_width=" wrap_content " android: layout_height=" wrap_content " android: layout_gravity="中心" android:文本="确认“/比; LinearLayout & lt; android: layout_width=" match_parent " android: layout_height=皐rap_content”比; & lt; TextView android: layout_width=" wrap_content " android: layout_height=" wrap_content " android:文本=" x + y=:“/比; & lt; TextView android: id=癅 + id/text1” android: layout_width=" wrap_content " android: layout_height=" wrap_content " android: layout_marginLeft=" 20 dp” android:输入textColor=" # 0五星级” android: ems=" 20 "/比; & lt;/LinearLayout> & lt;/LinearLayout>
2、下面是MainActivity.java的代码
包com.example.hjw.calculator; 进口android.support.v7.app.AppCompatActivity; 进口android.os.Bundle; 进口android.view.View; 进口android.widget.Button; 进口android.widget.EditText; 进口android.widget.TextView; 公开课MainActivity延伸AppCompatActivity { 私人TextView tv1 tv2; 私人EditText edt1 edt2; 私人按钮btn; @Override 保护无效onCreate(包savedInstanceState) { super.onCreate (savedInstanceState); setContentView (R.layout.activity_main); btn=(按钮)this.findViewById (R.id.btn); EditText edt1=() this.findViewById (R.id.edit1); EditText edt2=() this.findViewById (R.id.edit2); tv1=(TextView) this.findViewById (R.id.text1); btn。setOnClickListener(新View.OnClickListener () { @Override 公共空间onClick(查看v) { .toString字符串传递=edt1.getText () (); .toString字符串inputText2=edt2.getText () (); int num1=Integer.valueOf(传递).intValue (); int num2=Integer.valueOf (inputText2) .intValue (); num1=num1 + num2; inputText1=String.valueOf (num1); tv1.setText(传递); } }); } }
更多计算器功能实现,请点击专题:计算器功能汇总进行学习
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。