安卓中的标题/操作栏ID是什么?

5

我想尝试一下这个有趣的标题栏着色,但它对我不起作用。

getWindow().findViewById(android.R.id.title);

返回null。因此,我用层次结构查看器查看它,并发现该视图称为id/action_bar。但是没有R.id.action_bar(自动完成不提供它,也没有R.java中的类似内容)。

所以现在我感到更加困惑:

  • android.R.id.title现在有点过时了吗(我在模拟器中使用的是版本16)?
  • id/action_bar从哪里来?
  • 关于兼容性,有什么推荐的简单做法吗?

我应该获取ActionBarSherlock吗?我最初只想改变标题栏颜色...并不想大费周折。

2个回答

3

使用以下代码获取ActionBar的ID:

val actionBarId = resources.getIdentifier("action_bar", "id", packageName)

使用findViewById可以找到操作栏。

然后从操作栏的子项中查找标题(在正常情况下):

val actionbar = findViewById<ViewGroup>(actionBarId)
for (view in actionbar.children) {
    if (view is TextView) {
        // this is the titleView
    }
}

不过,如果你只想更改标题视图的文本,只需使用 getSupportActionBar

supportActionBar?.apply {
    // set title text
    title = "Hello"
    // set colored title text
    val coloredTitle = SpannableString("Hello")
    coloredTitle.setSpan(ForegroundColorSpan(Color.RED), 0, coloredTitle.length, 0)
    title = coloredTitle
}

1
如果您想要与 API 级别 14 / Android 4.0 之前的 Android 版本兼容,我建议使用 ActionBarSherlock。
更改 ActionBar 的背景很简单,最容易通过样式完成。请参阅http://android-developers.blogspot.com/2011/04/customizing-action-bar.html中的“背景”部分。
您也可以通过代码进行更改。将以下内容放入您的 onCreate() 中:
GradientDrawable gradientDrawable = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[] {Color.RED, Color.GREEN});
getActionBar().setBackgroundDrawable(gradientDrawable);

这是代码运行时的屏幕截图:

enter image description here


正如louielouie所说,您可以使用XML或Java来完成,但是对于这样的样式,XML更受欢迎,因为Android在活动仍在加载时应用您的样式,因此自定义样式不会延迟。 - Steven Schoen

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