Center align ActionBar title & use custom font as well

大憨熊 提交于 2019-12-24 18:17:15

问题


Absolute Android development beginner here, so please bear with me. I am trying to achieve 2 things with my title in the ActionBar:

  1. Center align the title text
  2. Use a custom font for the title text

I'm trying to follow this answer, so please look at that answer first.

Contents of MainActivity.java

    // ATTEMPT TO STYLE THE ACTIONBAR
    this.getActionBar().setDisplayShowCustomEnabled(true);
    this.getActionBar().setDisplayShowTitleEnabled(false);

    LayoutInflater inflator = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = inflator.inflate(R.layout.titleview, null);

    //if you need to customize anything else about the text, do it here.
    //I'm using a custom TextView with a custom font in my layout xml so all I need to do is set title
    ((TextView)v.findViewById(R.id.title)).setText(this.getTitle());

    //assign the view to the actionbar
    this.getActionBar().setCustomView(v);

I created a new XML file: layout/titleview.xml to correspond to R.layout.titleview above. It contains:

<com.muppethead.app.name.CustomTextView
    android:id="@+id/title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_marginLeft="10dp"
    android:textSize="20dp"
    android:maxLines="1"
    android:ellipsize="end"
    android:text="MY APP TITLE" />

This gives the error: The following classes could not be found: com.muppethead.app.name.CustomTextView

Question

Where am I going wrong? In addition to fixing the above error, where do I reference my font, which is located in assets/fonts/font.otf? And what about centering the text?

I gotta say, shame on Google for not making this possible from the XML. It removes the possibility for new developers to create anything attractive.

Thanks in advance for your help.


回答1:


What I would honestly do is forget about the custom TextView, and just use the default one in the XML. You're using it just this once, and only for the custom font.

You can do something like this instead:

TextView tv = (TextView) v.findViewById(R.id.title);
Typeface tf = Typeface.createFromFile(getAssets(), "fonts/font.otf");
tv.setTypeface(tf);
tv.setText(this.getTitle());


来源:https://stackoverflow.com/questions/13261755/center-align-actionbar-title-use-custom-font-as-well

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!