-2
所以我有這個代碼,現在我添加一個smiple動作到按鈕添加(setOnClickListener)當我運行應用程序它immidiatley崩潰... 任何想法爲什麼?應用程序崩潰後,使一個簡單的按鈕
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;
}
}
}
你的按鈕屬於片段佈局? – Raghunandan
正如@Raghunandan所說 - 最可能的原因是你的按鈕和textview在'fragment_main.xml'中,而不在'activity_main.xml'中。您只能使用'findViewById(...)'獲取當前佈局中的小部件的引用。您需要將用於獲取按鈕和textview的代碼與「OnClickListener」一起放入「Fragment」中。 – Squonk
看到http://stackoverflow.com/questions/23653778/nullpointerexception-accessing-views-in-oncreate – laalto