如果您的布局不满足按钮的 id(在您的情况下btnOK
),Eclipse 会抛出 NullPointerException - 它无法在您的布局内容中找到它。因此,当您设置布局(或菜单)时,它必须包含 id btnOK。核实!
将所有这些代码放入之后 将您的按钮初始化setContentView(R.layout.your_about_layout_name);
Button btnOK;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about);
btnOK = (Button)findViewById(R.id.btnOK);
btnok.setOnClickListener(OKListener);
}
更新:
看invertigo的回答:点击按钮改变布局是错误的。你必须这样做:
计算器活动
public class CalculatorActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calculator_black);
// initialization of your views stays here
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.calculator_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.your_id_to_go_in_about_activity:
Intent intent = new Intent(CalculatorActivity.this, AboutActivity.class);
// put some extras if you need to send information from this page to the
// AboutActivity page with this code: intent.putExtra();
startActivity(intent); // with this code you go to AboutActivity
return true;
case R.id.theme:
// Do Something with the theme
return true;
default:
return super.onOptionsItemSelected(item);
}
}
现在,你初始化 OKButton 的地方在新类中,我们称之为
AboutActivity
在这里你可以放我之前的代码:
public class AboutActivity extends Activity{
Button btnOK;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about);
btnOK = (Button)findViewById(R.id.btnOK);
btnok.setOnClickListener(OKListener);
}
// and the listener for your OK button have to look like this:
OnClickListener OKListener = new OnClickListener() {
@Override
public void onClick(View v) {
// Do something here if you need
finish(); // with finish() you are returning to the previous page
// which is CalculatorActivity
}
};
}