2014-01-16 74 views
0

我试图重现Google Keep,Gmail等ActionBar更改效果。操作栏更改效果

与图像波纹管一样,当用户选择笔记或邮件时,操作栏会使用其效果进行更改。 我想这样做。

任何帮助?

enter image description here

回答

1

看起来它是相对较新的能力,被称为Contextual action mode

简而言之,它只是针对长选项目的特定“上下文”菜单。我认为上面的链接提供了足够的信息。然而,下面是关于如何使用它的一些简单的例子:

main.xml中

<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_height="match_parent" 
    android:layout_width="match_parent" 
    android:clipChildren="false" 
    android:id="@+id/root"> 

    <Button 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/button" 
     android:text="Do Long Press" 
     android:layout_centerHorizontal="true" 
     android:layout_alignParentTop="true" 
     android:layout_marginTop="5dp" /> 
</RelativeLayout> 

context_menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item android:icon="@android:drawable/ic_menu_close_clear_cancel" 
      android:title="close" 
      android:showAsAction="always" 
      android:id="@+id/close_menu" /> 
</menu> 

MyActivity.java

public class MyActivity extends Activity implements ActionMode.Callback { 

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

     setContentView(R.layout.main); 

     findViewById(R.id.button).setOnLongClickListener(new View.OnLongClickListener() { 
      @Override 
      public boolean onLongClick(final View v) { 
       startActionMode(MyActivity.this); 
       return true; 
      } 
     }); 
    } 

    @Override 
    public boolean onCreateActionMode(final ActionMode mode, final Menu menu) { 
     // Inflate a menu resource providing context menu items 
     MenuInflater inflater = mode.getMenuInflater(); 
     inflater.inflate(R.menu.context_menu, menu); 
     return true; 
    } 

    @Override 
    public boolean onPrepareActionMode(final ActionMode mode, final Menu menu) { 
     // TODO: auto-generated block 
     return false; 
    } 

    @Override 
    public boolean onActionItemClicked(final ActionMode mode, final MenuItem item) { 
     switch (item.getItemId()) { 
      case R.id.close_menu: 
       mode.finish(); // Action picked, so close the CAB 
       return true; 
      default: 
       return false; 
     } 
    } 

    @Override 
    public void onDestroyActionMode(final ActionMode mode) { 
     // TODO: auto-generated block 
    } 
} 

它看起来像如下:

enter image description here

执行长按

enter image description here

请注意,V产品默认之一,在context_menu.xml我只提供了X项目。

+0

太棒了!我甚至不知道如何搜索这个组件......谢谢。 – Emerick