今天有一个个人应用程序的小想法。从来没有尝试过Android所以......任何帮助表示赞赏。
我想要的是 2 个输入字段,在点击 calc 按钮后将这些值和 * 它们相互对照给出结果。
对我来说看起来不错,但就像我说的那样,我对 Java 和 Android 的新手并不那么好。我的问题是当我点击 Calc 按钮时,它会强制关闭/停止工作。提前致谢!
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
>
<EditText android:id="@+id/fuel"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="@string/fuel" />
<EditText android:id="@+id/numLaps"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="@string/numLaps" />
<Button
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="@+id/calc"
android:text="@string/calc"
android:onClick="calc"/>
<EditText
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="@+id/output"
android:inputType="number"
/>
</LinearLayout>
MainActivity.java
package com.example.iracingfuelcalc;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements android.view.View.OnClickListener {
Button calc;
EditText numLaps,fuel, output;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fuel = (EditText)findViewById(R.id.fuel);
numLaps = (EditText)findViewById(R.id.numLaps);
output = (EditText)findViewById(R.id.output);
calc = (Button)findViewById(R.id.calc);
calc.setOnClickListener(this);
}
public void onClick(View arg0){
int fuelValue = -1;
try {
fuelValue = Integer.parseInt(fuel.getText().toString());
}
catch (NumberFormatException e)
{
//you don't have to do much here since fuelValue already has a default value (-1)
}
int lapsValue = -1;
try {
lapsValue = Integer.parseInt(numLaps.getText().toString());
}
catch (NumberFormatException e)
{
}
int result = 0;
result = fuelValue * lapsValue;
result += Integer.parseInt(output.getText().toString());
output.setText("" + result);
}
}
字符串.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">iRacing Fuel Calc</string>
<string name="fuel">Fuel per lap</string>
<string name="numLaps">Number of laps</string>
<string name="calc">Calculate</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_display_message">TEST</string>
<string name="output">0</string>
</resources>