以下是一个简单的安卓app开发实战案例:
我们将开发一个简单的计算器应用程序,该程序将能够执行基本的四则运算。
首先要做的是创建一个新项目。在Android Studio中,选择File ->New ->Project…,然后选择Empty Activity。然后输入项目名称和包名称,最后点击Finish按钮。
接下来,在我们的布局文件(activity_main.xml)中添加一些控件来表示计算器的布局。添加两个EditText,一个表示数字1,另一个表示数字2,以及四个Button,分别表示加、减、乘和除操作。
布局文件的代码如下所示:
```
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:ems="10" android:inputType="number" /> android:id="@+id/editText2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/editText1" android:layout_marginTop="20dp" android:layout_marginLeft="20dp" android:ems="10" android:inputType="number" />
```
接下来,我们需要在MainActivity.java中监听我们的四个Button,然后根据用户选择的操作执行相应的算术运算。我们还要显示运算结果。
在MainActivity.java中的代码如下所示:
```
public class MainActivity extends AppCompatActivity {
private EditText num1, num2;
private Button addButton, subtractButton, multiplyButton, divideButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
num1 = (EditText) findViewById(R.id.editText1);
num2 = (EditText) findViewById(R.id.editText2);
addButton = (Button) findViewById(R.id.addButton);
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int result = Integer.parseInt(num1.getText().toString()) +
Integer.parseInt(num2.getText().toString());
Toast.makeText(getApplicationContext(), "Result is " +
Integer.toString(result), Toast.LENGTH_LONG).show();
}
});
subtractButton = (Button) findViewById(R.id.subtractButton);
subtractButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int result = Integer.parseInt(num1.getText().toString()) -
Integer.parseInt(num2.getText().toString());
Toast.makeText(getApplicationContext(), "Result is " +
Integer.toString(result), Toast.LENGTH_LONG).show();
}
});
multiplyButton = (Button) findViewById(R.id.multiplyButton);
multiplyButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int result = Integer.parseInt(num1.getText().toString()) *
Integer.parseInt(num2.getText().toString());
Toast.makeText(getApplicationContext(), "Result is " +
Integer.toString(result), Toast.LENGTH_LONG).show();
}
});
divideButton = (Button) findViewById(R.id.divideButton);
divideButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int result = Integer.parseInt(num1.getText().toString()) /
Integer.parseInt(num2.getText().toString());
Toast.makeText(getApplicationContext(), "Result is " +
Integer.toString(result), Toast.LENGTH_LONG).show();
}
});
}
}
```
现在编译并运行代码,你将会看到一个计算器应用程序。
这是一个简单的安卓app开发实战案例,通过这个案例展示了安卓app开发的一些基本步骤。