Created
January 20, 2015 07:41
-
-
Save longkai/b4474389fc2b7c2f0151 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.imaygou.android.helper.drawable; | |
import android.graphics.drawable.Drawable; | |
import android.graphics.drawable.StateListDrawable; | |
import android.util.StateSet; | |
/** | |
* Created by longkai on 20/1/15. | |
*/ | |
public class StateListDrawableBuilder { | |
private static final int DEFAULT_CAPACITY = 2; | |
public static final int[] STATE_PRESSED = new int[]{android.R.attr.state_pressed}; | |
private int size; | |
private int[][] states; | |
private Drawable[] drawables; | |
public StateListDrawableBuilder() { | |
this.states = new int[DEFAULT_CAPACITY][]; | |
this.drawables = new Drawable[DEFAULT_CAPACITY]; | |
} | |
public StateListDrawableBuilder setStates(int[][] states) { | |
this.states = states; | |
this.size = states.length; | |
return this; | |
} | |
public StateListDrawableBuilder setDrawables(Drawable[] drawables) { | |
this.drawables = drawables; | |
this.size = states.length; | |
return this; | |
} | |
public StateListDrawableBuilder addState(int[] state, Drawable drawable) { | |
if (size + 1 == states.length) { | |
// expand the array | |
int[][] tmpStates = new int[states.length + 2][]; // plus 2 | |
System.arraycopy(states, 0, tmpStates, 0, states.length); | |
states = tmpStates; | |
Drawable[] tmpDrawables = new Drawable[states.length]; | |
System.arraycopy(drawables, 0, tmpDrawables, 0, drawables.length); | |
drawables = tmpDrawables; | |
} | |
states[size] = state; | |
drawables[size] = drawable; | |
size++; | |
return this; | |
} | |
public StateListDrawableBuilder addPressedState(Drawable drawable) { | |
return addState(STATE_PRESSED, drawable); | |
} | |
public StateListDrawableBuilder addDefaultState(Drawable drawable) { | |
return addState(StateSet.WILD_CARD, drawable); | |
} | |
public StateListDrawable build() { | |
if (states.length != drawables.length) { | |
throw new IllegalArgumentException("states' length must equals drawables' length"); | |
} | |
StateListDrawable listDrawable = new StateListDrawable(); | |
for (int i = 0; i < size; i++) { | |
listDrawable.addState(states[i], drawables[i]); | |
} | |
return listDrawable; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment