android - 如何使android操作栏标题居中对齐?

标签 android android-actionbar center

我尝试了自己的自定义操作栏,以使操作栏标题居中。有效。但是,在我在操作栏中添加选项菜单后,标题再次向左移动。我应该怎么做才能使标题居中于操作栏的中间? 我的代码是:

    ActionBar actionBar = getActionBar();
    actionBar.setDisplayHomeAsUpEnabled(false);
    actionBar.setDisplayShowCustomEnabled(true);
    actionBar.setDisplayShowTitleEnabled(false);    
    actionBar.setDisplayUseLogoEnabled(false);
    actionBar.setDisplayShowHomeEnabled(false);
    actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); 
    View cView = getLayoutInflater().inflate(R.layout.custom_actionbar, null);
    actionBar.setCustomView(cView);

我的布局是

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="@android:color/holo_blue_light"
android:orientation="vertical" >

<TextView
    android:id="@+id/apptitle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:layout_gravity="center_horizontal|center_vertical"
    android:gravity="center_horizontal|center_vertical"
    android:text="@string/app_name" />

最佳答案

我确定,您正在使用以下设置自定义主题。

getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); 
getSupportActionBar().setCustomView(R.layout.abs_layout);

如果没有,请添加第一行。自定义布局中的文本居中。 (重力 = 中心)

我还发现了一个类似的链接 herehere .希望这会有所帮助。

也试试这个。

我能够通过显示标题来完成我想要的 Activity ,而不是按照您的建议使用 customView。 key 我错过了一段时间是你必须使用 setCustomView(View, ActionVar.LayoutParams) 方法以获得自定义 View 居中,只需在自定义 View 中设置 layout_gravity="center" 布局文件不起作用。这是一个简短的代码 fragment ,展示了我如何 开始工作:

            TextView customView = (TextView)
LayoutInflater.from(this).inflate(R.layout.actionbar_custom_title_view_centered,
null);
            ActionBar.LayoutParams params = new
ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT,
ActionBar.LayoutParams.MATCH_PARENT, Gravity.CENTER);

            customView.setText("Some centered text");
            getSupportActionBar().setCustomView(customView, params);

此方法至少适用于 3.2、2.3 和 2.2 设备。

来源https://groups.google.com/forum/#!msg/actionbarsherlock/A9Ponma6KKI/Llsp41jWLEgJ

关于android - 如何使android操作栏标题居中对齐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21770428/

相关文章:

java - Android Studio : Creating a Swipe Tab Application that Reads Fragments. 强制关闭

android - 无法解析 : support-fragment error when add google architecture component dependency

android - 动态更改操作栏分隔线颜色(android :bottom for programmatically generated ShapeDrawable)?

html - 在响应式 div 框中将矢量图像居中?

html - 如何让这个 HTML 元素居中?

java - 调试配置 java.lang.NullPointerException 错误

android - 为什么 me.pushy.sdk.Pushy 在 Eclipse Indigo 中导致 NoClassDefFoundError?

android - Actionbar 列表导航宽度 - 换行内容

android - 在 Android 中检测溢出菜单中的点击?

css - 如何将显示为左浮动的几个div居中