实现效果
一、布局xml文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
tools:context=".MainActivity">
<EditText
android:id="@+id/EText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="请输入整数"
android:gravity="center"
/>
<TextView
android:id="@+id/fuhao1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+"
android:textSize="25sp"
android:layout_toRightOf="@+id/EText1"
/>
<EditText
android:id="@+id/EText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="请输入整数"
android:gravity="center"
android:layout_toRightOf="@+id/fuhao1"
/>
<TextView
android:id="@+id/fuhao2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="="
android:textSize="25sp"
android:layout_toRightOf="@+id/EText2"
/>
<TextView
android:id="@+id/t_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/fuhao2"
android:textSize="25sp"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="计算"
android:layout_below="@+id/EText1"
android:onClick="add"
/>
</RelativeLayout>
二、MainActivity.java文件
1.获取控件
2.创建add()方法进行运算
parseInt()函数可解析一个字符串,并返回一个整数。
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private EditText ET1,ET2;
private TextView t_result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ET1=(EditText)findViewById(R.id.EText1);
ET2=(EditText)findViewById(R.id.EText2);
t_result=(TextView) findViewById(R.id.t_result);
}
public void add(View view){
//获取输入的两个整数
String EText1=ET1.getText().toString().trim();
String EText2=ET2.getText().toString().trim();
//转换string为int,进行相加
if (EText1==null || EText1.isEmpty())
{
Toast.makeText(MainActivity.this,"请输入第一个整数",Toast.LENGTH_LONG).show();
return;
}
else if (EText2==null || EText2.isEmpty()){
Toast.makeText(MainActivity.this,"请输入第二个整数",Toast.LENGTH_LONG).show();
return;
}
else{
try{
int result=Integer.parseInt(EText1)+Integer.parseInt(EText2);
t_result.setText(""+result);
}
catch(Exception e){
Toast.makeText(MainActivity.this,"请输入正确的整数",Toast.LENGTH_LONG).show();
return;
}
}
}
}