我是一个全新的android开发新手,我只上了2节课。我的教授给出了一个迷你项目,创建了一个应用程序,它接受一些数字并计算餐费。这就是我到目前为止所知道的:
public class MainActivity extends AppCompatActivity {
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button cButton = (Button) findViewById(R.id.calculateButton);
cButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
//getting cost
EditText cost = (EditText)findViewById(R.id.mealCost);
String mealCost = cost.getText().toString();
int mealCostInt = Integer.parseInt(mealCost);
//getting tax percentage
EditText tax = (EditText)findViewById(R.id.tax);
String taxAmount = cost.getText().toString();
int taxAmountInt = Integer.parseInt(mealCost);
//getting tip percentage
EditText tip = (EditText)findViewById(R.id.tip);
String tipAmount = cost.getText().toString();
int tipAmountInt = Integer.parseInt(mealCost);
//calculating total amount
int totalAmount = (mealCostInt)+((taxAmountInt/100)*mealCostInt)+((tipAmountInt/100)*mealCostInt);
//displaying total amount
EditText total = (EditText)findViewById(R.id.total);
total.setText(totalAmount);
}
}
);
}
}
每次我运行代码时,应用程序都会成功加载。但是,每当我单击calculate按钮时,我都会看到下面的错误:
--------- beginning of crash
09-18 20:25:40.169 2752-2752/com.example.shameemah.mealcalculator E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.shameemah.mealcalculator, PID: 2752
java.lang.ClassCastException: android.support.v7.widget.AppCompatTextView cannot be cast to android.widget.EditText
at com.example.shameemah.mealcalculator.MainActivity$1.onClick(MainActivity.java:35)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
我已经搜索了类似的错误,并尝试了一些我看到的解决方案,但由于我的知识有限,我不确定我到底应该做什么。我将非常感谢一些详细的解释来帮助我。我正在努力学习和理解一些东西,所以请回答,就像你在和一个没有android开发经验的人说话一样。非常感谢!
发布于 2016-09-18 20:56:50
我认为,您在xml布局中的一个视图(mealCost、tax或tips)是TextView小部件。这就是隐式转换导致错误的原因。在xml中更改EditText上的TextView,错误必须消失。
https://stackoverflow.com/questions/39562461
复制相似问题