Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android ViewAnimator/ViewFlipper/ViewSwitcher and hardcoded value for setDisplayedChild

I am going to work with one of:

  • ViewAnimator
  • ViewFlipper
  • ViewSwitcher

All of them have a method setDisplayedChild to change a view from one to another.

Only argument of that method is int whichChild - a number of view in the view queue.

Is it possible to work with any sort of not hardcoded numbers ?

I want to be able to call:

setDisplayedChild(R.id.SettingsView)

instead of:

setDisplayedChild(3)
like image 211
hsz Avatar asked Mar 31 '11 20:03

hsz


2 Answers

You can use the indexOfChild(View child) method:

viewAnimator.setDisplayedChild( viewAnimator.indexOfChild( findViewById(R.id.SettingsView) ) );
like image 140
Nonoo Avatar answered Nov 10 '22 17:11

Nonoo


These classes are just ViewGroup extensions that keep the child list in and array of View.

You could easily extend whatever one you want to look through the list of views for the Id. (untested code follows)

class myFlipper extends ViewFlipper {

    public myFlipper(Context context) {
        super(context);
    }

    int getChildById(int id) {
        int childindex = -1;
        int i = 0;
        while (i<getChildCount()) {
            View v = getChildAt(i);
            if (v.getId()==id) {
                childindex = i;
                break;
            }
            i++;
        }
        return childindex;
    }

    void setDisplayedChildById(int id) {
        int i = getChildById(id);
        if (i != -1) {
            setDisplayedChild(i);
        }
    }
}
like image 36
slund Avatar answered Nov 10 '22 18:11

slund