Android 居中对齐操作栏标题&;也可以使用自定义字体

Android 居中对齐操作栏标题&;也可以使用自定义字体,android,customization,android-actionbar,Android,Customization,Android Actionbar,这里绝对是Android开发的初学者,所以请耐心听我说。我试图用我在ActionBar中的标题实现两件事: 将标题文本居中对齐 为标题文本使用自定义字体 我正试着按照答案,所以请先看那个答案 MainActivity.java的内容 // ATTEMPT TO STYLE THE ACTIONBAR this.getActionBar().setDisplayShowCustomEnabled(true); this.getActionBar().setDisplaySh

这里绝对是Android开发的初学者,所以请耐心听我说。我试图用我在ActionBar中的标题实现两件事:

  • 将标题文本居中对齐
  • 为标题文本使用自定义字体
  • 我正试着按照答案,所以请先看那个答案

    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);
    
    我创建了一个新的XML文件:layout/titleview.XML对应于上面的
    R.layout.titleview
    。它包括:

    <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" />
    
    
    
    这会产生以下错误:
    找不到以下类:com.muppethead.app.name.CustomTextView

    问题

    我哪里做错了?除了修复上述错误,我在哪里引用我的字体,它位于
    资产/font/font.otf
    ?那么文本居中呢

    我得说,谷歌没有从XML中实现这一点,真是太遗憾了。它消除了新开发人员创建任何有吸引力的东西的可能性


    提前感谢您的帮助。

    老实说,我会忘记自定义的
    TextView
    ,只使用XML中的默认值。您只使用了这一次,并且仅用于自定义字体

    您可以这样做:

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

    您是否创建了类
    com.muppethead.app.name.CustomTextView
    ?没有。解决此错误的选项之一是创建类。我真的不确定类中会发生什么,以及需要设置TBH的属性。好的,请原谅我不得不将其简化。你能概述一下我需要做些什么才能从我现在的位置达到你的建议吗?我知道我应该删除我的
    MainActivity.java
    中的代码,然后使用你的代码。另外,我应该完全删除
    titleview.xml
    。但是
    R.id.title
    (来自您的代码)如何对应于ActionBar标题?我可以用你的方法将文本居中对齐吗?不,不,保留
    titleview.xml
    。将
    com.muppethead.app.name.CustomTextView
    替换为
    TextView
    。在现有文件中唯一要替换的是
    setText
    行(用我提供的代码替换该行)。成功了。我唯一需要更改的是
    createFromFile
    createFromAsset
    ——我知道这一点的唯一原因是因为我事先尝试了其他人的代码。谢谢你的帮助,伙计!你很擅长这个。知道如何将文本居中吗?应该能够在XML中设置
    android:gravity=“center”
    。如果对你有用的话,我会把它添加到我的帖子中。不,不幸的是,它不起作用(尽管如此,你还是应该得到答案。