我對Android開發非常陌生。哪裏聲明onOptionsItemSelected全球使用?
在我MainActivity.java
文件,我已經聲明的onOptionsItemSelected(MenuItem menu)
方法,它允許用戶將當前頁面MainActivity.java
和另一頁我創建了名爲Settings.java
之間跳轉。
當用戶轉到Settings.java
頁面,並且他們點擊菜單中的Home
選項時,沒有任何反應。我知道這是因爲onOptionsItemSelected(MenuItem menu)
僅在MainActivity.java
類中定義,而不在Settings.java
類中定義。
我現在通過將onOptionsItemSelected(MenuItem menu)
從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();
}
}
Settings.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);
}
}
}
謝謝。我結束了使用'BaseActivity'選項。我會在不久的將來看看碎片。 – FilmiHero 2013-03-27 18:23:31