我对 Android 开发非常陌生。
在我的MainActivity.java
文件中,我声明了一个onOptionsItemSelected(MenuItem menu)
方法,允许用户在当前MainActivity.java
页面和我创建的另一个页面之间跳转,名为Settings.java
.
当用户进入该Settings.java
页面并单击Home
菜单中的选项时,什么也没有发生。我知道这是因为onOptionsItemSelected(MenuItem menu)
仅在类中定义MainActivity.java
而不在Settings.java
类中定义。
我现在通过将onOptionsItemSelected(MenuItem menu)
from复制MainActivity.java
到Settings.java
. 但这是非常多余的。
我应该在哪里声明可以在不同类中重用的方法?
MainActivity.java
public class MainActivity extends Activity {
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@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) {
switch (item.getItemId()) {
case R.id.action_settings:
showMsg("Settings Clicked");
this.startActivity(new Intent(this, Settings.class));
return true;
case R.id.action_home:
showMsg("Home clicked");
this.startActivity(new Intent(this, MainActivity.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void showMsg(String msg) {
Toast toast = Toast.makeText(this.getBaseContext(), msg, Toast.LENGTH_LONG);
toast.show();
}
}
设置.java
public class Settings extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
}
@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) {
switch (item.getItemId()) {
case R.id.action_settings:
this.startActivity(new Intent(this, Settings.class));
return true;
case R.id.action_home:
this.startActivity(new Intent(this, MainActivity.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}