Android自定义操作栏未填充父级,标题不对中

时间:2013-10-15 17:16:56

标签: java android user-interface android-actionbar

我一直在尝试以下问题:我创建了一个自定义操作栏:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/com_facebook_blue" >

<TextView 
    android:id="@+id/action_bar_title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:maxLines="1"
    android:layout_marginLeft="@dimen/activity_horizontal_margin"
    android:layout_centerInParent="true"
    android:textSize="30dp"
    android:textColor="#ffffff"
    android:text="@string/app_title"/>

</RelativeLayout>

由GraphicsBuilder类以下列方式膨胀:

public static void setupActionBar(String title, Activity a) {

        final ViewGroup actionBarLayout = (ViewGroup) a.getLayoutInflater()
                .inflate(R.layout.action_bar_layout, null);
        final ActionBar actionBar = a.getActionBar();

        actionBar.setDisplayShowHomeEnabled(false);
        actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setDisplayShowCustomEnabled(true);
        actionBar.setCustomView(actionBarLayout);
        final int actionBarColor = a.getResources().getColor(R.color.main_red);
        actionBar.setBackgroundDrawable(new ColorDrawable(actionBarColor));

        TextView tv = (TextView) actionBarLayout.findViewById(R.id.action_bar_title);
        Typeface font = Typeface.createFromAsset(a.getAssets(), "fonts/Molle-Regular.ttf");
        tv.setText(title);
        tv.setTypeface(font);
    }

这导致以下结果(我将标题栏背景保持为蓝色以突出显示问题):

enter image description here

基本上看起来自定义操作栏没有填充父宽度,因此任何尝试在中心对齐标题都是无用的。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:10)

我知道这已经很久了。 通过在设置为自定义视图后更改布局参数来解决它。

我的逻辑是,当你第一次给它充气时,它会假定原始容器的大小。 当你打电话:

actionBar.setCustomView(titlebar);

已预设尺寸。 我的解决方案是:

View titlebar = inflater.inflate(R.layout.titlebar, null);

// Do stuff to Title Bar //

ActionBar actionBar = getActionBar();
actionBar.setCustomView(titlebar);
View v = actionBar.getCustomView();
LayoutParams lp = v.getLayoutParams();
lp.width = LayoutParams.MATCH_PARENT;
v.setLayoutParams(lp);

或者,您可以先设置操作栏布局而不使用inflater:

ActionBar actionBar = getActionBar();
actionBar.setCustomView(R.id.titlebar);
View v = actionBar.getCustomView();
// Do something to the view  E.g Set button listeners blah //

// Rest of code
相关问题