Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The title/action bar ID in android?

I wanted to try out this funny title bar coloring, but it doesn't work for me as

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

returns null. So I had a look at it with Hierarchy Viewer and found out that the view is called id/action_bar instead. But there's no R.id.action_bar (autocomplete doesn't offer it and there's nothing like this is R.java).

So now I'm doubly confused:

  • Is android.R.id.title sort of obsolete now (I'm using version 16 in my emulator)?
  • Where does id/action_bar come from?
  • What's the recommended and simple practice w.r.t. compatibility?

Should I get ActionBarSherlock? I originally just wanted to change the title bar color... not fool around with it a lot.

like image 682
maaartinus Avatar asked Nov 04 '22 13:11

maaartinus


1 Answers

Use the code below to get the ActionBar's id:

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

And use findViewById you can find the action bar.

Then find the title from actionbar's children (in normal cases):

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

However, if you just want to change the title view's text, just use 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
}
like image 107
Sam de Jong Avatar answered Nov 15 '22 01:11

Sam de Jong