Java tutorial
//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 { /** * Sets the color for a view with a colored background. In case the view's * background is not a {@link ColorDrawable}, or does not contain a * color-drawable in one of its layers, nothing happens. * * @param view * @param color */ public static void setColor(View view, int color) { ColorDrawable colorDrawable = getColorDrawableBackground(view); if (colorDrawable != null) { colorDrawable.setColor(color); } } /** * 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; } }