How do I programmatically set the background color gradient on a Custom Title Bar?

To do this in code, you create a GradientDrawable.
The only chance to set the angle and color is in the constructor.
If you want to change the color or angle, just create a new GradientDrawable and set it as the background

    View layout = findViewById(R.id.mainlayout);

    GradientDrawable gd = new GradientDrawable(
            GradientDrawable.Orientation.TOP_BOTTOM,
            new int[] {0xFF616261,0xFF131313});
    gd.setCornerRadius(0f);

    layout.setBackgroundDrawable(gd);

For this to work, I added an id to your main LinearLayout as follows

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainlayout"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
<ImageView   
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:src="https://stackoverflow.com/questions/6115715/@drawable/title_bar_logo"
              android:gravity="center_horizontal"
              android:paddingTop="0dip"/>

</LinearLayout>

And to use this as for a custom title bar

    getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.custom_title_bar);
    View title = getWindow().findViewById(R.id.mainlayout);
    title.setBackgroundDrawable(gd);

Leave a Comment