2013-10-15 29 views
3

我一直在嘗試了以下問題:我創建了一個自定義操作欄:Android的自定義操作欄不填寫父母,標題不居中對齊

<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

基本上它看起來像自定義操作欄不填充父寬度,因此任何嘗試對齊標題在中心是沒有用的。我怎樣才能解決這個問題?

回答

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

或者,您可以先設置操作欄佈局不充氣:

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 
+0

可以正常使用,+1 –

+0

醫生給你開! +1 –

+0

如何通過支持操作欄執行此操作? –