簡體   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