maaartinus
maaartinus

Reputation: 46482

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:

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

Upvotes: 5

Views: 5169

Answers (2)

Steven de Jong
Steven de Jong

Reputation: 199

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
}

Upvotes: 3

louielouie
louielouie

Reputation: 14941

I would recommend using ActionBarSherlock if you're looking for compatibility with Android versions before API level 14 / Android 4.0.

Changing the background of the ActionBar is straightforward and is most easily done via styles. See the "Background" section of http://android-developers.blogspot.com/2011/04/customizing-action-bar.html

You can also change it via code. Put this in your onCreate():

GradientDrawable gradientDrawable = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[] {Color.RED, Color.GREEN});
getActionBar().setBackgroundDrawable(gradientDrawable);

Here is a screenshot of this code in action:

enter image description here

Upvotes: 1

Related Questions