0

我想設置自定義字體,但總是出現textview爲空的錯誤。這裏是我的代碼:無法設置自定義字體的操作欄標題

int titleId = getResources().getIdentifier("action_bar_title", "id", "android"); 
TextView yourTextView = (TextView) findViewById(titleId); 
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/barrett_normal.ttf"); 

獲得以下錯誤:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setTypeface(android.graphics.Typeface)' on a null object reference 

這是我onCreate()方法:

@Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     try { 
      getSupportActionBar().setDisplayShowTitleEnabled(false); 
      getSupportActionBar().setDisplayShowCustomEnabled(true); 
      int titleId = getResources().getIdentifier("action_bar_title", "id", "android"); 
      tv = (TextView) findViewById(titleId); 
      tf = Typeface.createFromAsset(getAssets(), "fonts/barrett_normal.ttf"); 
      tv.setTypeface(tf); 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     setActionBarTitle(this.getTitle()); 
    } 
+0

顯示您的OnCreate代碼和XML –

+0

到這裏看看:http://stackoverflow.com/questions/8607707/how-to-set-a-custom-font-in-the-actionbar-title –

+0

@Aditya我在'onCreate()'方法中只寫了很多代碼 –

回答

1

嘗試這種方式

SpannableString s = new SpannableString("My Title"); 
s.setSpan(new TypefaceSpan(this, "MyTypeface.otf"), 0, s.length(), 
     Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 

// Update the action bar title with the TypefaceSpan instance 
ActionBar actionBar = getActionBar(); 
actionBar.setTitle(s); 

檢查hereTypefaceSpan

+0

什麼是'txtvw'? –

+0

您在xml中擁有的textview的id。可以顯示您的xml嗎? –

+0

我得到'ID'像這樣:'int titleId = getResources()。getIdentifier(「action_bar_title」,「id」,「android」);' –