Skip to content

Instantly share code, notes, and snippets.

@JakeWharton
Created June 13, 2012 17:59
Show Gist options
  • Save JakeWharton/2925529 to your computer and use it in GitHub Desktop.
Save JakeWharton/2925529 to your computer and use it in GitHub Desktop.
ViewAnimator helper which allows setting the selected child by ID rather than index
package com.squareup.widgets;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ViewAnimator;
/** ViewAnimator helper which allows setting the selected child by ID rather than index. */
public class SquareViewAnimator extends ViewAnimator {
public SquareViewAnimator(Context context) {
super(context);
}
public SquareViewAnimator(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* Set the currently displayed child by its ID.
*
* @param id ID of child.
* @throws IllegalArgumentException If child with specified ID does not exist.
*/
public void setDisplayedChildById(int id) {
for (int i = getChildCount() - 1; i >= 0; i--) {
View child = getChildAt(i);
if (child.getId() == id) {
if (i != getDisplayedChild()) {
setDisplayedChild(i);
}
return;
}
}
throw new IllegalArgumentException("View with ID " + id + " not found.");
}
/** Get the view ID of the currently displayed child. */
public int getDisplayedChildId() {
return getChildAt(getDisplayedChild()).getId();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment