我是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);
}
}
);
}
}
每次运行代码时,应用程序都会成功加载。但是,每当我点击计算按钮时,我都会看到如下错误:
--------- 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 dev没有经验的人交谈。非常感谢你!
答案 0 :(得分:1)
我认为,xml布局中的一个观点(mealCost,tax或tips)是TextView小部件。这就是隐式转换导致错误的原因。在xml中更改EditText上的TextView,错误必须消失。