4

我想将标题放在操作栏中的中心,同时在它旁边有操作图标(并忽略它们以进行重力设置)。

我想要这个: 在此处输入图像描述

相反,我有这个: 在此处输入图像描述

这是我的代码:

    ActionBar actionBar = getSupportActionBar();

    ActionBar.LayoutParams params = new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.MATCH_PARENT);

    actionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.top_bar));
    actionBar.setCustomView(LayoutInflater.from(this).inflate(R.layout.actionbar_layout, null), params); 
    actionBar.setDisplayShowCustomEnabled(true);
    actionBar.setDisplayShowHomeEnabled(false);
    actionBar.setDisplayShowTitleEnabled(false);

我的布局:

<?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:orientation="vertical" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:padding="8dp"
        android:src="@drawable/launcher_icon" />

    <TextView
        android:id="@+id/actionbar_title"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:maxHeight="1dp"
        android:maxLines="1"
        android:paddingLeft="48dp"
        android:paddingRight="48dp"
        android:text="Bacon ipsum"
        android:textColor="#777777"
        android:textSize="20sp" />

</RelativeLayout>

所以我的问题是,只有标题居中才有效,如果我旁边有 0 个操作栏项目,只要我添加一个项目,居中就会搞砸。如果我可以使用向上功能按钮(现在也搞砸了居中),那也很棒。

任何帮助,将不胜感激。

我不想实现自己的操作栏项/按钮逻辑。

4

3 回答 3

3

您可以在 TextView 中尝试:

<TextView
    android:id="@+id/actionbar_title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:maxHeight="1dp"
    android:maxLines="1"
    android:paddingLeft="48dp"
    android:paddingRight="48dp"
    android:text="Bacon ipsum"
    android:textColor="#777777"
    android:textSize="20sp" />
于 2013-05-13T14:12:39.803 回答
2
  1. 从您的 RelativeLayout 中删除启动器图标。
  2. 将 RelativeLayout 的宽度更改为wrap_content
  3. 消除:

    actionBar.setDisplayShowCustomEnabled(true); actionBar.setDisplayShowHomeEnabled(false); actionBar.setDisplayShowTitleEnabled(false);

  4. 添加:

    ActionBar.LayoutParams lp = new ActionBar.LayoutParams(
    
    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, Gravity.CENTER);
    
    actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM)
    actionBar.setCustomView(yourInflatedCustomView, lp);
    
于 2014-03-07T15:27:40.420 回答
0

您是否尝试过将此代码实现到文本中?

android:layout_centerHorizontal="true"
于 2013-05-13T14:00:17.057 回答