这是创建自定义的示例MenuItem
为了ActionBar
.
First:创建View
这将作为你的MenuItem
.
ActionLayout示例
/**
* 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");
}
}
Second:创建您将实际应用到的布局MenuItem
.
动作布局示例
<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
在你的布局中。通常当您长按 aMenuItem
带有图标的工具提示会显示该内容MenuItem
是为了.对于您的情况,您需要采取额外的步骤来确保此工具提示仍然可以访问。
一个很好的帮手是罗曼·努里克 (Roman Nurik) 的备忘单 https://gist.github.com/romannurik/3982005。您可以看到我如何在操作布局的构造函数中使用它。
您专门询问了MenuItem
是可选择的。为此,请确保包含android:background="?android:attr/selectableItemBackground"
and android:clickable="true"
属性。
Third: 使用android:actionLayout
属性来设置布局并正常在您的范围内扩展菜单Activity
or Fragment
.
你的菜单
<item
android:id="@+id/action_typeface"
android:actionLayout="@layout/action_layout_example"
android:showAsAction="ifRoom"
android:title="@string/hello_world"/>
使用MenuItem
In onCreateOptionsMenu
call MenuItem.getActionView
and on 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
}
});
结果