2014-10-01 73 views
2

我用ShowcaseView這樣的:ShowcaseView突出錯誤的項目

ActionItemTarget target = new ActionItemTarget(this, R.id.menu_search); 

ShowcaseView sv = new ShowcaseView.Builder(this, true) 
       .setTarget(target) 
       .setContentText("Press this to search") 
       .setStyle(R.style.CustomShowcaseTheme) 
       .build(); 

但是當我開始應用第一,ShowcaseView突出home鍵。當我嘗試再次啓動應用程序時,顯示正確的ActionBar項目。 我的應用程序不使用ActionbarSherlock等兼容性庫。

任何想法爲什麼會發生這種情況?

+0

你是什麼意思的「再次啓動應用程序」。你強迫關閉它並打開它,或者你重新打開它調用onPause + onResume?此外,你什麼時候調用這個代碼?因爲'R.id.menu_search'可能當時還沒有可用 – 2014-10-01 15:31:50

+0

@PedroOliveira我在onCreate()中調用它。顯然這是一個錯誤的地方。 – 2014-10-01 15:43:35

+0

使用此代碼的最佳位置將放在onCreateOptionsMenu上,即使在那裏'R.id.menu_search'也不會指向視圖,因爲它尚未被充氣,所以您將不得不找到一種方法來在那裏不使用ID。 – 2014-10-01 15:46:07

回答

3

按照要求:

的問題是,你正在試圖獲取一個id的觀點,即不在層次呢。根據活動查看週期,僅在onCreate之後創建菜單。最好的解決方案是使用onCreateOptionsMenu,但即使在這裏,R.id.menu_search也不會返回有效的ID,因爲菜單尚未創建。由於事件順序在API lv16中已經改變,我建議你稍微修改一下。您可以在您的onCreate()上創建一個處理程序並執行postDelayed可運行。代碼將在菜單設計完成後執行。在那個可運行的,你可以檢索R.id.menu_search的視圖,並突出顯示它。

0

我會嘗試在這裏提出的示例代碼:

@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); 

    new ShowcaseView.Builder(this) 
      .withMaterialShowcase() 
      .setTarget(new ToolbarActionItemTarget(this.toolbar, R.id.menu_search)) 
      .setContentText("Here's how to highlight items on a toolbar") 
      .build() 
      .show(); 

    return true; 
} 

注:工具欄聲明爲類的成員。