2014-10-01 75 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; 
} 

注:工具栏声明为类的成员。