所以我有这个代码,现在我添加了一个简单的动作到按钮添加(setOnClickListener),当我运行应用程序时,它立即崩溃... 知道为什么吗?
public class MainActivity extends ActionBarActivity {
int counter;
Button add,sub;
TextView display;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counter = 0;
add = (Button)findViewById(R.id.bAdd);
sub = (Button)findViewById(R.id.bSub);
display = (TextView)findViewById(R.id.tvDisplay);
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
display.setText("Your Total is " + counter);
}
});
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
@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;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
答案 0 :(得分:0)
最有可能是你的
add = (Button)findViewById(R.id.bAdd);
正在返回null
。尝试通过打印验证这一点
Log.d("TEST", "is null: " + (add == null));
下一步是确保您的 activity_main XML中确实定义了ID为“bAdd”的Button。编辑您的问题以添加您的XML文件activity_main
。