如何在ActionBar标题中设置自定义字体?

269

如果可能的话,我该如何在ActionBar标题文本(仅限标题文本,而不是选项卡文本)中使用位于assets文件夹中的字体设置自定义字体? 我不想使用android:logo选项。

17个回答

3
如果你想在整个 Activity 中设置所有 TextView 的字体,可以使用类似以下的内容:
public static void setTypefaceToAll(Activity activity)
{
    View view = activity.findViewById(android.R.id.content).getRootView();
    setTypefaceToAll(view);
}

public static void setTypefaceToAll(View view)
{
    if (view instanceof ViewGroup)
    {
        ViewGroup g = (ViewGroup) view;
        int count = g.getChildCount();
        for (int i = 0; i < count; i++)
            setTypefaceToAll(g.getChildAt(i));
    }
    else if (view instanceof TextView)
    {
        TextView tv = (TextView) view;
        setTypeface(tv);
    }
}

public static void setTypeface(TextView tv)
{
    TypefaceCache.setFont(tv, TypefaceCache.FONT_KOODAK);
}

还有字体缓存:

import java.util.TreeMap;

import android.graphics.Typeface;
import android.widget.TextView;

public class TypefaceCache {

    //Font names from asset:
    public static final String FONT_ROBOTO_REGULAR = "fonts/Roboto-Regular.ttf";
    public static final String FONT_KOODAK = "fonts/Koodak.ttf";

    private static TreeMap<String, Typeface> fontCache = new TreeMap<String, Typeface>();

    public static Typeface getFont(String fontName) {
        Typeface tf = fontCache.get(fontName);
        if(tf == null) {
            try {
                tf = Typeface.createFromAsset(MyApplication.getAppContext().getAssets(), fontName);
            }
            catch (Exception e) {
                return null;
            }
            fontCache.put(fontName, tf);
        }
        return tf;
    }

    public static void setFont(TextView tv, String fontName)
    {
        tv.setTypeface(getFont(fontName));
    }
}

2

不需要自定义TextView!

首先,在您的Java代码中禁用工具栏中的标题:     getSupportActionBar()。setDisplayShowTitleEnabled(false);

然后,在工具栏中简单地添加一个TextView:

<android.support.v7.widget.Toolbar
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    app:popupTheme="@style/AppTheme.PopupOverlay">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/app_name"
        android:textSize="18sp"
        android:fontFamily="@font/roboto" />

    </android.support.v7.widget.Toolbar>

这将无法与最新的导航 UI Jetpack 库一起使用。 - Ali Asheer

2

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);

1

更新正确答案。

首先:将标题设置为false,因为我们正在使用自定义视图。

    actionBar.setDisplayShowTitleEnabled(false);

其次:创建titleview.xml。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:background="@android:color/transparent" >

    <TextView
       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="" />

</RelativeLayout>

最后:
//font file must be in the phone db so you have to create download file code
//check the code on the bottom part of the download file code.

   TypeFace font = Typeface.createFromFile("/storage/emulated/0/Android/data/"   
    + BuildConfig.APPLICATION_ID + "/files/" + "font name" + ".ttf");

    if(font != null) {
        LayoutInflater inflator = LayoutInflater.from(this);
        View v = inflator.inflate(R.layout.titleview, null);
        TextView titleTv = ((TextView) v.findViewById(R.id.title));
        titleTv.setText(title);
        titleTv.setTypeface(font);
        actionBar.setCustomView(v);
    } else {
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle("  " + title); // Need to add a title
    }

下载字体文件:因为我将文件存储在Cloudinary中,所以我有一个链接可以下载它。

/**downloadFile*/
public void downloadFile(){
    String DownloadUrl = //url here
    File file = new File("/storage/emulated/0/Android/data/" + BuildConfig.APPLICATION_ID + "/files/");
    File[] list = file.listFiles();
    if(list == null || list.length <= 0) {
        BroadcastReceiver onComplete = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                try{
                    showContentFragment(false);
                } catch (Exception e){
                }
            }
        };

        registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(DownloadUrl));
        request.setVisibleInDownloadsUi(false);
        request.setDestinationInExternalFilesDir(this, null, ModelManager.getInstance().getCurrentApp().getRegular_font_name() + ".ttf");
        DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        manager.enqueue(request);
    } else {
        for (File files : list) {
            if (!files.getName().equals("font_name" + ".ttf")) {
                BroadcastReceiver onComplete = new BroadcastReceiver() {
                    @Override
                    public void onReceive(Context context, Intent intent) {
                        try{
                            showContentFragment(false);
                        } catch (Exception e){
                        }
                    }
                };

                registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(DownloadUrl));
                request.setVisibleInDownloadsUi(false);
                request.setDestinationInExternalFilesDir(this, null, "font_name" + ".ttf");
                DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
                manager.enqueue(request);
            } else {
                showContentFragment(false);
                break;
            }
        }
    }
}

1
为了补充@Sam_D的回答,我必须这样做才能使其正常工作:
this.setTitle("my title!");
((TextView)v.findViewById(R.id.title)).setText(this.getTitle());
TextView title = ((TextView)v.findViewById(R.id.title));
title.setEllipsize(TextUtils.TruncateAt.MARQUEE);
title.setMarqueeRepeatLimit(1);
// in order to start strolling, it has to be focusable and focused
title.setFocusable(true);
title.setSingleLine(true);
title.setFocusableInTouchMode(true);
title.requestFocus();

看起来有点过度 - 引用 v.findViewById(R.id.title)) 两次 - 但这是我唯一能做到的方式。


0
我们需要使用反射来实现这个。
final int titleId = activity.getResources().getIdentifier("action_bar_title", "id", "android");

    final TextView title;
    if (activity.findViewById(titleId) != null) {
        title = (TextView) activity.findViewById(titleId);
        title.setTextColor(Color.BLACK);
        title.setTextColor(configs().getColor(ColorKey.GENERAL_TEXT));
        title.setTypeface(configs().getTypeface());
    } else {
        try {
            Field f = bar.getClass().getDeclaredField("mTitleTextView");
            f.setAccessible(true);
            title = (TextView) f.get(bar);
            title.setTextColor(Color.BLACK);
            title.setTypeface(configs().getTypeface());
        } catch (NoSuchFieldException e) {
        } catch (IllegalAccessException e) {
        }
    }

-1

试试这个

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);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接