【问题标题】:Unable to set action bar title with custom font无法使用自定义字体设置操作栏标题
【发布时间】:2016-03-24 07:23:31
【问题描述】:

我正在尝试设置自定义字体,但总是收到 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());
    }

【问题讨论】:

标签: android nullpointerexception android-actionbar textview android-assets


【解决方案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);

检查here 是否有TypefaceSpan

【讨论】:

  • 你在你的xml中的textview的id..你能显示你的xml吗?
  • 我收到ID 是这样的:int titleId = getResources().getIdentifier("action_bar_title", "id", "android");
  • 这就是为什么我要求提供完整的活动代码。你是否在 oncreate 中添加了 setcontentview 方法?
  • 我不需要在 oncreate 方法中setcontentview。我刚刚设置了我的操作栏标题。
  • 我看不到您的操作栏在哪里?请输入您的活动代码..或者按照此android--examples.blogspot.in/2015/09/… 以编程方式创建文本视图,如 TextView tv = new TextView(getApplicationContext());
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-27
  • 1970-01-01
  • 1970-01-01
  • 2013-12-04
  • 1970-01-01
  • 2014-06-16
相关资源
最近更新 更多