Tuesday, September 22, 2015

android - How to create gradient background ActionBar

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    tools:context=".MainActivity"
    android:background="#d0d1be"
    >
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Make Gradient ActionBar"
        android:layout_marginTop="10dp"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.graphics.Color;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.app.ActionBar;
import android.graphics.drawable.GradientDrawable;


public class MainActivity extends Activity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the widgets reference from XML layout
        RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
        final Button btn = (Button) findViewById(R.id.btn);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Get the ActionBar
                ActionBar ab = getActionBar();

                // Create a gradient drawable programmatically
                GradientDrawable gradient = new GradientDrawable();
                gradient.setColors(new int[]{
                        Color.parseColor("#feffe9"),
                        Color.parseColor("#fff600"),
                        Color.parseColor("#feffe9"),
                });

                gradient.setGradientType(GradientDrawable.LINEAR_GRADIENT);
                gradient.setShape(GradientDrawable.RECTANGLE);
                gradient.setStroke(2, Color.parseColor("#cbb700"));

                // Set the ActionBar background
                ab.setBackgroundDrawable(gradient);
           }
        });
    }
}
More android examples