【问题标题】:Center align ActionBar title & use custom font as well居中对齐 ActionBar 标题并使用自定义字体
【发布时间】:2012-11-07 00:53:56
【问题描述】:

这里是绝对的Android开发初学者,所以请多多包涵。我正在尝试用我在 ActionBar 中的标题来实现两件事:

  1. 居中对齐标题文本
  2. 为标题文本使用自定义字体

我正在尝试关注this 的答案,所以请先查看该答案。

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

这给出了错误: The following classes could not be found: com.muppethead.app.name.CustomTextView

问题

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

我得说,Google 很遗憾没有通过 XML 实现这一点。它消除了新开发人员创造任何有吸引力的东西的可能性。

提前感谢您的帮助。

【问题讨论】:

  • 你创建了com.muppethead.app.name.CustomTextView这个类吗?
  • 不,我没有。解决此错误的选项之一是创建类。我不太确定课程中的内容以及设置 TBH 需要哪些属性。

标签: android customization android-actionbar


【解决方案1】:

老实说,我会忘记自定义 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());

【讨论】:

  • 好的,请原谅我不得不把这件事弄得一团糟。你能概述一下我需要做什么才能从我所在的地方到你建议的地方吗?我知道我应该删除MainActivity.java 中的代码并使用您的代码。另外,我应该完全删除titleview.xml。但是R.id.title(来自您的代码)如何对应于 ActionBar 标题?我可以使用您的方法将文本居中对齐吗?
  • 不不不,保持titleview.xml。将com.muppethead.app.name.CustomTextView 替换为TextView。在现有文件中唯一要替换的是 setText 行(用我提供的代码替换该行)。
  • 天才。那行得通。我唯一需要更改的是 createFromFilecreateFromAsset - 我知道这一点的唯一原因是因为我事先尝试过其他人的代码。谢谢你的帮助伙计!你在这方面很出色。知道如何使文本居中吗?
  • 应该可以在 XML 中设置android:gravity="center"。如果对您有用,我会将其添加到我的帖子中。
  • 不,很遗憾,这不起作用。 :( 不过,你应该得到答案。
猜你喜欢
  • 2013-08-06
  • 1970-01-01
  • 2013-03-26
  • 2012-01-26
  • 2016-12-26
  • 2013-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多