2011-03-18 32 views
6

我知道有兩種方法來設置活動的標題。一種方法是在Android清單中將其設置爲這樣:android:label =「@ string/app_name」。其次是以編程方式設置活動類,如setTitle(「Hello World!」)。這兩種方式都位於左側,但我怎麼能把它放在中心?如何將活動中的標題或標籤對齊?

回答

5

您將需要定義自定義標題樣式/主題。在示例中查找com.example.android.apis.app.CustomTitle。

+0

[AndroidRuntimeException(HTTP://計算器。 com/q/11254366):您不能將自定義標題與其他標題功能組合在一起。 – ateiob 2012-06-29 12:05:47

+0

@ateiob - 是的,這個想法是,如果你想在自定義標題中使用「其他標題功能」,你必須自己將這些功能構建到自定義標題中。 Android無法知道如何組合股票特徵,除非它也控制標題本身。 – 2012-06-29 15:43:59

5

我發現設置標題中心的另一種方式,只要把代碼中的setContentView(R.layout.new)下...

((TextView)((FrameLayout)((LinearLayout)((ViewGroup) getWindow().getDecorView()).getChildAt(0)).getChildAt(0)).getChildAt(0)).setGravity(Gravity.CENTER); 

希望這有助於。謝謝!

+0

@ ef2011,沒問題! – exception01 2011-05-24 03:31:07

+14

唯一的問題是,它依賴於窗口內容結構的未記錄方面。谷歌已經知道從根本上改變無證的數據結構,並且不能保證這種特定的技術將來會有效。 – 2011-08-14 05:03:04

+3

那麼,谷歌糟糕(在os設計),它不適合我。但是這樣做:((TextView)((LinearLayout)((ViewGroup)getWindow()。getDecorView())。getChildAt(0))。getChildAt(0))。setGravity(Gravity.CENTER); – HardCoder 2012-06-09 10:58:33

21

它會正常工作..

TextView customView = (TextView) 
LayoutInflater.from(this).inflate(R.layout.actionbar_custom_title_view_centered, 
    null); 

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

customView.setText("Some centered text"); 
getSupportActionBar().setCustomView(customView, params); 
+0

這個答案是正確的 – JesperB 2012-11-02 15:39:12

+0

你太棒了!感謝分享。 – Kid24 2013-03-06 12:22:24

+0

這隻適用於API 11+。大多數手機仍然<2.3.4。 – Chloe 2013-05-19 22:35:06

1
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); // must come before setContentView 
    setContentView(R.layout.activity_calculator); 
    getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_bar); 

把你的佈局,佈局/ title_bar.xml

<?xml version="1.0" encoding="utf-8"?> 
<TextView 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/myTitle" 
    android:text="Custom Centered Title" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:textColor="@android:color/black" 
    android:gravity="center" 
    /> 

http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android-apps/2.2_r1.1/com/example/android/apis/app/CustomTitle.java

+0

我正在使用minSdk 14.但這不適用於我。看到我的問題:http://stackoverflow.com/questions/17605282/center-title-of-activity-in-android-action-bar – 2013-07-12 00:42:19