我是android的新手(不是java的新手)。尝试遵循已过时的教程。我不知道为什么setOnClickListener会使该应用程序崩溃。我知道某个地方存在空指针异常,但是我不确定如何解决它。另外,在旁注中,为什么我的Class扩展ActionBarActivity而不是Activity,就像到目前为止我看到的所有示例一样?
public class StartingPoint extends ActionBarActivity {
int counter;
Button add, sub;
TextView display;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_starting_point);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
} // end of if
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) {
counter++;
display.setText("Counter equals" + 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.starting_point, 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_starting_point,
container, false);
return rootView;
}
}
}
最佳答案
您的按钮和textview处于片段布局,而不是 Activity 布局,因此您必须将代码移至onCreateView:
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
int counter=0;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
Button add = (Button) rootView.findViewById(R.id.bAdd);
Button sub = (Button) rootView.findViewById(R.id.bSub);
TextView display = (TextView) rootView.findViewById(R.id.tvDisplay);
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
display.setText("Counter equals" + counter);
}
});
return rootView;
}
}
另外,您必须清除onCreate,然后离开:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_starting_point);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}