13

我想將自定義字體應用於顯示在ActionBar上的應用程序的標題。以前我沒有使用任何支持庫和這個解決方案:如何在使用AppCompat時更改ActionBar標題字體

int titleId = getResources().getIdentifier("action_bar_title", "id", 
       "android"); 
TextView yourTextView = (TextView) findViewById(titleId); 
yourTextView.setTypeface(face); 

對我來說很好。但是現在我正在使用材質設計SupportActionBar並引發NullPointerException。那麼如何在使用AppCompat時更改ActionBar字體?

+1

這回應我認爲你可以幫助http://stackoverflow.com/a/15181195/2778639 –

+0

@ user27799謝謝,這篇文章解決了我的問題。如果有人遇到類似問題,只需使用鏈接帖子中的方法,該方法與支持庫v-21一起工作良好。 – fragon

+0

解決方案在這裏,[動作條定製設計。] [1] [1]:http://stackoverflow.com/questions/17966350/changing-the-font-of-the-application-title-在android/21480484#21480484 – Karthikeyan

回答

-2

準備自定義佈局,把文本視圖中action_bar_layout,然後調用 actionbar.setcustomlayout()

5

您已經成功地使用程序兼容性V22 + 的新的工具欄和要導入android.support假設。 v7.widget.Toolbar在您的活動中。

所以在你的OnCreate你應該已經有

toolbar = (Toolbar) findViewById(R.id.toolbar); 
setSupportActionBar(toolbar); 

在這一點上,你幾乎完成:

進口java.lang.reflect.Field中;

,並添加以下行:

TextView yourTextView = null; 
try { 
    Field f = toolbar.getClass().getDeclaredField("mTitleTextView"); 
    f.setAccessible(true); 
    yourTextView = (TextView) f.get(toolbar); 
    yourTextView.setTypeface(face); 
} catch (NoSuchFieldException e) { 
} catch (IllegalAccessException e) { 
} 
+1

爲我工作。謝謝 – QuantumTiger

1

使用工具欄,而不是ActionBar.follow以下步驟添加工具欄:從文件菜單,轉到庫 1.更改你的應用程序的主題,Theme.AppCompat.Light.NoActionBar 2.Goto項目結構依賴關係,添加設計庫並同步您的項目。 3.Goto佈局要顯示動作條,寫下面的代碼:

<android.support.v7.widget.Toolbar 
    android:id="@+id/mytoolbar" 
    android:layout_width="match_parent" 
    android:layout_height="56dp" 
    android:background="@color/pccolor" 
    android:title="Services" 
    app:titleTextAppearance="@style/Toolbar.TitleText" 
    android:elevation="4dp"> 
    <TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Toolbar Title" 
    android:layout_gravity="center" 
    android:id="@+id/toolbar_title" /> 
</android.support.v7.widget.Toolbar> 

4.In的活動,如下面寫:

Toolbar mytoolbar=(Toolbar)findViewById(R.id.mytoolbar); 
    setSupportActionBar(mytoolbar); 

要自定義您的標題字體:

fontPath = "Fonts/Roboto-Light.ttf"; 
    Typeface tf = Typeface.createFromAsset(getActivity().getAssets(), fontPath); 

TextView tv_ins=(TextView)FindViewById(R.id.toolbar_title); 
tv_ins.setText("mytitle"); 
tv_ins.setTypeface(tf); 

試試這個希望這可以幫助你,如果有什麼不妥,請讓我知道。

相關問題