下面是为ActionBar 创建自定义MenuItem 的示例。
首先:创建将用作您的MenuItem 的View。
ActionLayoutExample
/**
* A {@link RelativeLayout} that serves as a custom {@link MenuItem}
*/
public class ActionLayoutExample extends RelativeLayout {
/** The MenuItem */
private TextView mHello;
/**
* Constructor for <code>ActionLayoutExample</code>
*
* @param context The {@link Context} to use
* @param attrs The attributes of the XML tag that is inflating the view
*/
public ActionLayoutExample(Context context, AttributeSet attrs) {
super(context, attrs);
// Ensure the MenuItem is accessible
CheatSheet.setup(this);
}
/**
* {@inheritDoc}
*/
@Override
protected void onFinishInflate() {
super.onFinishInflate();
// Initialize the TextView
mHello = (TextView) findViewById(android.R.id.text1);
mHello.setTypeface(myTypeface);
mHello.setText("Hello");
}
}
第二:创建您将实际应用于MenuItem 的布局。
action_layout_example
<your.package.name.ActionLayoutExample xmlns:android="http://schemas.android.com/apk/res/android"
style="?android:attr/actionButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="?android:attr/selectableItemBackground"
android:clickable="true"
android:contentDescription="@string/hello_world" >
<TextView
android:id="@android:id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</your.package.name.ActionLayoutExample>
包含style="?android:attr/actionButtonStyle" 样式很重要,以确保布局正确反映ActionBar 项目。在布局中包含android:contentDescription 也很重要。通常,当您长按带有图标的MenuItem 时,会显示一个工具提示以指示MenuItem 的用途。在您的情况下,您需要采取额外的步骤来确保仍然可以访问此工具提示。
Roman Nurik's CheatSheet 是一个很好的帮手。你可以在动作布局的构造函数中看到我是如何使用它的。
您特别询问了MenuItem 是可选的。为此,请确保包含 android:background="?android:attr/selectableItemBackground" 和 android:clickable="true" 属性。
第三:使用android:actionLayout 属性设置布局并在Activity 或Fragment 中正常扩展菜单。
your_menu
<item
android:id="@+id/action_typeface"
android:actionLayout="@layout/action_layout_example"
android:showAsAction="ifRoom"
android:title="@string/hello_world"/>
使用MenuItem
在onCreateOptionsMenu 中调用MenuItem.getActionView 和View.onClickListener。这是因为 onOptionsItemSelected 不会被自定义 View 调用
final View example = menu.findItem(R.id.action_typeface).getActionView();
example .setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Do something
}
});
结果