我正在尝试在 android 模拟器上运行此应用程序,但它显示“不幸的是,该应用程序已停止工作”:
package com.example.myapp;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
static int counter;
static Button badd, bsub;
static TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counter=0;
badd=(Button)findViewById(R.id.button1);
bsub=(Button)findViewById(R.id.button2);
text=(TextView) findViewById(R.id.textView1);
badd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
text.setText("your total is :"+counter);
}
});
bsub.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter--;
text.setText("your total is :"+counter);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
xml代码:
<RelativeLayout 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"
android:gravity="start"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="your total is 0"
android:textSize="65sp"
/>
<Button
android:id="@+id/button1"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_gravity="center"
android:text="add"
/>
<Button
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button2"
android:layout_below="@+id/textView1"
android:layout_marginLeft="117dp"
android:text="subtract" />
</RelativeLayout>
日志猫显示如下:
由 java.lang.nullpointexception 引起