How to Set a Custom Font in the ActionBar Title?

后端 未结 17 1518
面向向阳花
面向向阳花 2020-11-22 09:46

How (if possible) could I set a custom font in a ActionBar title text(only - not the tab text) with a font in my assets folder? I don\'t want to use the android:logo option.

相关标签:
17条回答
  • 2020-11-22 10:10
        ActionBar actionBar = getSupportActionBar();
        TextView tv = new TextView(getApplicationContext());
        Typeface typeface = ResourcesCompat.getFont(this, R.font.monotype_corsiva);
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT, // Width of TextView
                RelativeLayout.LayoutParams.WRAP_CONTENT); // Height of TextView
        tv.setLayoutParams(lp);
        tv.setText("Your Text"); // ActionBar title text
        tv.setTextSize(25);
        tv.setTextColor(Color.WHITE);
        tv.setTypeface(typeface, typeface.ITALIC);
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        actionBar.setCustomView(tv);
    
    0 讨论(0)
  • 2020-11-22 10:12

    It's an ugly hack but you can do it like this (since action_bar_title is hidden) :

        try {
            Integer titleId = (Integer) Class.forName("com.android.internal.R$id")
                    .getField("action_bar_title").get(null);
            TextView title = (TextView) getWindow().findViewById(titleId);
            // check for null and manipulate the title as see fit
        } catch (Exception e) {
            Log.e(TAG, "Failed to obtain action bar title reference");
        }
    

    This code is for post-GINGERBREAD devices but this can be easily extended to work with actionbar Sherlock as well

    P.S. Based on @pjv comment there's a better way to find action bar title id

    final int titleId = 
        Resources.getSystem().getIdentifier("action_bar_title", "id", "android");
    
    0 讨论(0)
  • 2020-11-22 10:13

    The Calligraphy library let's you set a custom font through the app theme, which would also apply to the action bar.

    <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
    <item name="android:textViewStyle">@style/AppTheme.Widget.TextView</item>
    </style>
    
    <style name="AppTheme.Widget"/>
    
    <style name="AppTheme.Widget.TextView" parent="android:Widget.Holo.Light.TextView">
       <item name="fontPath">fonts/Roboto-ThinItalic.ttf</item>
    </style>
    

    All it takes to activate Calligraphy is attaching it to your Activity context:

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(new CalligraphyContextWrapper(newBase));
    }
    

    The default custom attribute is fontPath, but you may provide your own custom attribute for the path by initializing it in your Application class with CalligraphyConfig.Builder. Usage of android:fontFamily has been discouraged.

    0 讨论(0)
  • 2020-11-22 10:13

    TRY THIS

    public void findAndSetFont(){
            getActionBar().setTitle("SOME TEST TEXT");
            scanForTextViewWithText(this,"SOME TEST TEXT",new SearchTextViewInterface(){
    
                @Override
                public void found(TextView title) {
    
                } 
            });
        }
    
    public static void scanForTextViewWithText(Activity activity,String searchText, SearchTextViewInterface searchTextViewInterface){
        if(activity == null|| searchText == null || searchTextViewInterface == null)
            return;
        View view = activity.findViewById(android.R.id.content).getRootView();
        searchForTextViewWithTitle(view, searchText, searchTextViewInterface);
    }
    
    private static void searchForTextViewWithTitle(View view, String searchText, SearchTextViewInterface searchTextViewInterface)
    {
        if (view instanceof ViewGroup)
        {
            ViewGroup g = (ViewGroup) view;
            int count = g.getChildCount();
            for (int i = 0; i < count; i++)
                searchForTextViewWithTitle(g.getChildAt(i), searchText, searchTextViewInterface);
        }
        else if (view instanceof TextView)
        {
            TextView textView = (TextView) view;
            if(textView.getText().toString().equals(searchText))
                if(searchTextViewInterface!=null)
                    searchTextViewInterface.found(textView);
        }
    }
    public interface SearchTextViewInterface {
        void found(TextView title);
    }
    
    0 讨论(0)
  • 2020-11-22 10:16

    Try using This

    TextView headerText= new TextView(getApplicationContext());
    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
    headerText.setLayoutParams(lp);
    headerText.setText("Welcome!");
    headerText.setTextSize(20);
    headerText.setTextColor(Color.parseColor("#FFFFFF"));
    Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/wesfy_regular.ttf");
    headerText.setTypeface(tf);
    getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
    getSupportActionBar().setCustomView(headerText);
    
    0 讨论(0)
  • 2020-11-22 10:17

    From Android Support Library v26 + Android Studio 3.0 onwards, this process has become easy as a flick!!

    Follow these steps to change the font of Toolbar Title:

    1. Read Downloadable Fonts & select any font from the list (my recommendation) or load a custom font to res > font as per Fonts in XML
    2. In res > values > styles, paste the following (use your imagination here!)

      <style name="TitleBarTextAppearance" parent="android:TextAppearance">
          <item name="android:fontFamily">@font/your_desired_font</item>
          <item name="android:textSize">23sp</item>
          <item name="android:textStyle">bold</item>
          <item name="android:textColor">@android:color/white</item>
      </style>
      
    3. Insert a new line in your Toolbar properties app:titleTextAppearance="@style/TextAppearance.TabsFont" as shown below

      <android.support.v7.widget.Toolbar
          android:id="@+id/toolbar"
          android:layout_width="match_parent"
          android:layout_height="?attr/actionBarSize"
          android:background="?attr/colorPrimary"
          app:titleTextAppearance="@style/TitleBarTextAppearance"
          app:popupTheme="@style/AppTheme.PopupOverlay"/>
      
    4. Enjoy Custom Actionbar Title font styling!!

    0 讨论(0)
提交回复
热议问题