这是 java 类中使用的代码。它在 eclipse 中没有显示任何错误。logcat 显示空指针异常和类种姓异常
package com.myfirstapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
public class MyfirstappActivity extends Activity {
/** Called when the activity is first created. */
int count ;
Button add,sub;
TextView txt;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
count = 0;
add = (Button) findViewById(R.id.add_one);
sub = (Button) findViewById(R.id.sub_one);
txt = (Button) findViewById(R.id.display);
setContentView(R.layout.main);
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
count = count + 1;
txt.setText("Your total is " + count);
}
});
sub.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
count = count - 1;
txt.setText("Your total is " + count);
}
});
}
这是创建的 main.xml 布局文件。我同时尝试清理项目。尝试使用 try catch 机制。当我评论引用上述代码部分的按钮时,应用程序运行良好
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1">
<TextView
android:layout_width="fill_parent"
android:layout_height="60dp"
android:text="@string/hello"
android:id="@+id/display"
android:textSize="40dp"
android:gravity="center" />
<Button
android:text="@string/add1"
android:layout_gravity="center"
android:layout_width="fill_parent"
android:layout_height="60dp"
android:id="@+id/add_one"
android:textSize="40dp"
android:gravity="center">
</Button>
<Button
android:text="@string/sub1"
android:layout_gravity="center"
android:layout_width="fill_parent"
android:layout_height="60dp"
android:id="@+id/sub_one"
android:textSize="40dp"
android:gravity="center">
</Button>
</LinearLayout>