繁体   English   中英

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

[英]Android Custom Action bar not filling parent, title not center aligned

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

<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);
    }

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

在此输入图像描述

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

我知道这已经很久了。 一旦将布局参数设置为自定义视图,就可以通过更改布局参数来解决它。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM