ActionBar徽标居中,操作项在两侧。

35

我该如何制作一个位于中心具有标志的操作栏,两侧有两个操作项,像这样?

图片描述

我将使用 ActionBar Sherlock。

1个回答

39

我在评论中提到,我不确定任何这些内容是否会因为ABS而改变(我敢肯定不会有太大变化),但使用标准的操作栏,你可以为你的操作栏标题加载一个自定义的布局.xml。例如,你可以有action_bar_title.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/your_desired_background" >

<TextView
        android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:maxLines="1"
            android:ellipsize="end"
            android:text="@string/app_name"
            android:textAppearance="?android:attr/textAppearanceMedium"/>

</RelativeLayout>

接下来,在您的 Activity 中,您想要在 onCreate() 中调用以下方法:

private void setupActionBar() {
        ActionBar ab = getActionBar();
        ab.setDisplayShowCustomEnabled(true);
        ab.setDisplayShowTitleEnabled(false);
        ab.setIcon(R.drawable.your_left_action_icon);
        LayoutInflater inflator = (LayoutInflater) this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflator.inflate(R.layout.action_bar_title, null);

        TextView titleTV = (TextView) v.findViewById(R.id.title);
        Typeface font = Typeface.createFromAsset(getAssets(),
                "fonts/your_custom_font.ttf");
        titleTV.setTypeface(font);

        ab.setCustomView(v);

            ab.setHomeAsUpEnabled(true);
    }

为了控制左侧的操作项,你可以在你的Activity中这样做:

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.yourRightActionItem:
                        //do something
                        return true;
        case android.R.id.home: //<-- this will be your left action item
            // do something
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
当然,确保您还要对菜单xml中的其他必要操作项进行设置。这将适用于任何右侧操作项。
编辑:刚才在另一个评论中看到您说标题将是一张图片。如果是这种情况,请使用您的ImageView替换我在示例中使用的TextView,并忽略setupActionBar()方法中的字体自定义代码。
编辑2:我更新了Java代码。您需要执行ab.setHomeAsUpEnabled(true),然后使用自定义主题来实现一个无形的(或者可能是@null,虽然我不知道Android是否会接受)可绘制的向上指示器作为主页。请参见此处(取自答案here :))。
<style name="Theme.MyFancyTheme" parent="android:Theme.Holo">
    <item name="android:homeAsUpIndicator">@drawable/my_fancy_up_indicator</item>
    <!-- or you could try @null -->
</style>

如何在Sherlock中完成?我想支持API10。 - Kaloyan Roussev
有没有可能只在Application类中执行一次,而不是在每个Activity中都执行?怎么做? - Pranav Mahajan
1
实际上,我们应该创建自己的MyActivity扩展Activity,并在那里执行它一次。 - Pranav Mahajan
@dennisdrew 谢谢你的解决方案。但是有没有办法让下拉菜单的标题居中呢?(不仅仅是标题)? - Mahdi
只有在添加actionBar.setDisplayShowCustomEnabled(true);之后,这项功能才对我有效。 - Sharone Lev
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接