2014-04-01 148 views
2

我有10個活動擴展了baseActivity。我的BaseActivity基本上有一個幫助菜單圖標。當用戶按下幫助菜單圖標時,我應該顯示該活動的幫助菜單。我怎樣才能知道哪些活動稱爲幫助菜單,所以我知道該XML資源顯示如何知道哪個活動點擊了按鈕?

public class BaseActivity extends Activity { 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     MenuInflater inflater = getMenuInflater(); 
     inflater.inflate(R.menu.help_menu, menu); 
     return true; 
    } 
    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle item selection 
     switch (item.getItemId()) { 
      case R.id.help_menu_item: 
        displayHelpMenu();   
       return true; 

      default: 
       return super.onOptionsItemSelected(item); 
     } 
    } 

    protected void displayHelpMenu(){ 

      // I will load the xml to the textview and display it in dialog. How can I know which xml resource to load 

    } 
} 

回答

3

一種方法找出Activity是使用instanceOf。這樣的事情:

protected void displayHelpMenu() { 
    // I will load the xml to the textview and display it in dialog. 
    // How can I know which xml resource to load 

    if(this instanceOf DerivedActivity.class) { 
     // load XML file 
    } 
    else if(...) { 
    ... 
    } 
} 

但是,在我看來,雖然這解決了你的問題,但這不是正確的做事方式。在面向對象的情況下,你應該使用方法覆蓋

base class定義加載資源的一般功能,而派生類應提供要加載的文件的名稱。換句話說,base class不應該知道derived class。一個更好的解決辦法是:

protected void displayHelpMenu() { 

    // ask each child class for the help menu resource file 
    int resId = getHelpMenuResource(); 

    // write code to load XML file with resId 
    ... 
    ... 
} 

protected int getHelpMenuResource() { 
    return defaultMenuId; 
} 

現在在派生類中,@OverridegetHelpMenuResource()方法並返回特定於該活動的資源ID。

+0

偉大的解決方案。我喜歡替代品..接受:) – Snake

1

如何使您的BaseActivity抽象並添加getMenuResource方法?

public abstract class BaseActivity extends Activity { 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     MenuInflater inflater = getMenuInflater(); 
     inflater.inflate(R.menu.help_menu, menu); 
     return true; 
    } 
    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle item selection 
     switch (item.getItemId()) { 
      case R.id.help_menu_item: 
        displayHelpMenu();   
       return true; 

      default: 
       return super.onOptionsItemSelected(item); 
     } 
    } 

    protected void displayHelpMenu(){ 

      // I will load the xml to the textview and display it in dialog. How can I know which xml resource to load 
     int menuResourceId = getMenuResourceId(); 
     // do the rest 
    } 

    public abstract int getMenuResourceId(); 
} 
+0

謝謝。好的解決方案,但其他人擊敗你:) – Snake

相關問題