create StateListDrawable - Android Graphics

Android examples for Graphics:State List Drawable

Description

create StateListDrawable

Demo Code


//package com.java2s;
import android.annotation.SuppressLint;
import android.content.Context;

import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.os.Build;

public class Main {
    public static StateListDrawable createStateListDrawable(
            Context context, int normalResourceId, int activeResourceId) {
        Drawable drawableNormal = getDrawable(context, normalResourceId);
        Drawable drawableActive = getDrawable(context, activeResourceId);
        return createStateListDrawable(context, drawableNormal,
                drawableActive, drawableActive, drawableActive,
                drawableNormal);//ww  w  .ja v  a 2 s  . c o m
    }

    public static StateListDrawable createStateListDrawable(Context contet,
            Drawable normal, Drawable selected, Drawable pressed,
            Drawable focused, Drawable unable) {

        StateListDrawable drawableList = new StateListDrawable();
        drawableList.addState(new int[] { android.R.attr.state_pressed,
                android.R.attr.state_enabled }, pressed);
        drawableList.addState(new int[] { android.R.attr.state_enabled,
                android.R.attr.state_focused }, focused);
        drawableList.addState(new int[] { android.R.attr.state_selected },
                selected);
        drawableList.addState(new int[] { android.R.attr.state_focused },
                focused);
        drawableList.addState(
                new int[] { android.R.attr.state_window_focused }, unable);
        drawableList.addState(new int[] { android.R.attr.state_enabled },
                normal);
        drawableList.addState(new int[] {}, normal);

        return drawableList;

    }

    @SuppressWarnings("deprecation")
    @SuppressLint("NewApi")
    public static Drawable getDrawable(Context context, int resourceId) {

        if (Build.VERSION.SDK_INT >= 21) {
            return context.getDrawable(resourceId);
        } else {
            return context.getResources().getDrawable(resourceId);
        }
    }

    public static Drawable getDrawable(Context context, int resourceId,
            int convertToColor) {
        Drawable drawable = getDrawable(context, resourceId);
        return changeDrawableColor(drawable, convertToColor);

    }

    public static Drawable changeDrawableColor(Drawable drawable,
            int destinationColor) {
        drawable.setColorFilter(destinationColor,
                android.graphics.PorterDuff.Mode.MULTIPLY);
        return drawable;
    }
}

Related Tutorials