Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*******************************************************************************
 * Copyright 2012-present Pixate, Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/

import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.view.View;

public class Main {
    /**
     * Returns the background color value for a View that have a
     * {@link ColorDrawable} background, or a {@link LayerDrawable} background
     * that contains one.
     * 
     * @param view
     * @return The view's background color. -1 in case the view does not have a
     *         ColorDrawable background.
     */
    public static int getColor(View view) {
        ColorDrawable colorDrawable = getColorDrawableBackground(view);
        if (colorDrawable != null) {
            return colorDrawable.getColor();
        }
        return -1;
    }

    /**
     * Returns the View's {@link ColorDrawable} background in case it has one.
     * The {@link ColorDrawable} may be set directly as the View's background,
     * or nested within a {@link LayerDrawable}. In case of a
     * {@link LayerDrawable}, the method will return the first color-drawable it
     * finds.
     * 
     * @param view
     * @return A {@link ColorDrawable}, or <code>null</code> in case not found.
     */
    private static ColorDrawable getColorDrawableBackground(View view) {
        if (view != null) {
            Drawable background = view.getBackground();
            if (background instanceof ColorDrawable) {
                return (ColorDrawable) background;
            }
            if (background instanceof LayerDrawable) {
                LayerDrawable layeredBG = (LayerDrawable) background;
                int numberOfLayers = layeredBG.getNumberOfLayers();
                for (int i = 0; i < numberOfLayers; i++) {
                    if (layeredBG.getDrawable(i) instanceof ColorDrawable) {
                        return (ColorDrawable) layeredBG.getDrawable(i);
                    }
                }
            }
        }
        return null;
    }
}