анимация не работает для первого элемента галереи Android - PullRequest
0 голосов
/ 18 мая 2011

Я использовал галерею.Каждый элемент галереи занимает всю ширину экрана.Я также поместил кнопку, чтобы щелкнуть.Когда первый элемент отображается в галерее, если я нажимаю кнопку флип, он не показывает анимацию флип.Но если я прокручиваю галерею и перехожу к другому элементу или возвращаюсь снова к первому элементу, анимация работает правильно.Может кто-нибудь догадаться, в чем проблема.

Я вызываю метод flipView с позицией выбранного элемента.Методы и классы для анимации приведены ниже:

public void flipView(int position) {
    applyRotation(0, 90, position);
    isFrontShowing[position] = !isFrontShowing[position];       
}

private void applyRotation(float start, float end, int position) {
    // Find the center of image
    final float centerX, centerY;
    if(isFrontShowing[position] == true) {
        centerX = detailsLayout[position].getMeasuredWidth() / 2.0f;
        centerY = detailsLayout[position].getMeasuredHeight() / 2.0f;
        detailsLayout[position].requestFocus();
        detailsLayout[position].bringToFront();
    } else {
        centerX = scriptLayout[position].getMeasuredWidth() / 2.0f;
        centerY = scriptLayout[position].getMeasuredHeight() / 2.0f;
        scriptLayout[position].requestFocus();
        scriptLayout[position].bringToFront();
    }


    final Rotate3dAnimation rotation =
        new Rotate3dAnimation(start, end, centerX, centerY, 200.0f, true);
    rotation.setDuration(350);
    rotation.setFillAfter(true);
    rotation.setInterpolator(new LinearInterpolator());
    rotation.setAnimationListener(new DisplayNextView(isFrontShowing[position], detailsLayout[position], scriptLayout[position]));

    if (isFrontShowing[position] == true)
    {
        detailsLayout[position].startAnimation(rotation);
    } else {
        //System.out.println("---Backward flipping started...");

        scriptLayout[position].startAnimation(rotation);
    }

}



import android.view.animation.Animation;

import android.view.animation.Transformation;импорт android.graphics.Camera;import android.graphics.Matrix;

открытый класс Rotate3dAnimation extends Animation {private final float mFromDegrees;закрытый финал float mToDegrees;закрытый финал поплавок mCenterX;закрытый финал поплавок mCenterY;закрытый финал float mDepthZ;приватный финальный булев mReverse;Частная камера mCamera;public Rotate3dAnimation (с плавающей точкой от градусов, с плавающей точкой до градусов, с плавающей точкой X, с плавающей точкой Y, глубиной с плавающей точкой Z, логическим обратным) {mFromDegrees = fromDegrees;mToDegrees = toDegrees;mCenterX = centerX;mCenterY = centerY;mDepthZ = глубина Z;mReverse = обратный;}

@Override
public void initialize(int width, int height, int parentWidth, int parentHeight) {
    super.initialize(width, height, parentWidth, parentHeight);
    mCamera = new Camera();
}

@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
    final float fromDegrees = mFromDegrees;
    float degrees = fromDegrees + ((mToDegrees - fromDegrees) * interpolatedTime);

    final float centerX = mCenterX;
    final float centerY = mCenterY;
    final Camera camera = mCamera;

    final Matrix matrix = t.getMatrix();

    camera.save();
    if (mReverse) {
        camera.translate(0.0f, 0.0f, mDepthZ * interpolatedTime);
    } else {
        camera.translate(0.0f, 0.0f, mDepthZ * (1.0f - interpolatedTime));
    }
    camera.rotateY(degrees);
    camera.getMatrix(matrix);
    camera.restore();

    matrix.preTranslate(-centerX, -centerY);
    matrix.postTranslate(centerX, centerY);
}

}

package com.vocabAhead.SATVocab;

import android.view.animation.Animation;import android.widget.RelativeLayout;

открытый финальный класс DisplayNextView реализует Animation.AnimationListener {private boolean mCurrentView;RelativeLayout layout1;RelativeLayout layout2;

public DisplayNextView(boolean currentView, RelativeLayout layout1,
        RelativeLayout layout2) {
    mCurrentView = currentView;
    this.layout1 = layout1;
    this.layout2 = layout2;
}

public void onAnimationStart(Animation animation) {

}

public void onAnimationEnd(Animation animation) {
    if(mCurrentView == true)
        layout1.post(new SwapViews(mCurrentView, layout1, layout2));        
    else
        layout2.post(new SwapViews(mCurrentView, layout1, layout2));
}

public void onAnimationRepeat(Animation animation) {
}

}

package com.vocabAhead.SATVocab;

import android.view.View;импорт android.view.animation.Animation;import android.view.animation.LinearInterpolator;import android.view.animation.Animation.AnimationListener;import android.widget.RelativeLayout;

открытый финальный класс SwapViews реализует Runnable {private boolean mIsFirstView;RelativeLayout layout1;RelativeLayout layout2;

public SwapViews(boolean isFirstView, RelativeLayout layout1, RelativeLayout layout2) {
    mIsFirstView = isFirstView;
    this.layout1 = layout1;
    this.layout2 = layout2;
}

public void run() {
    final float centerX, centerY;
    if(mIsFirstView) {
        centerX = layout1.getWidth() / 2.0f;
        centerY = layout1.getHeight() / 2.0f;
    } else {
        centerX = layout2.getWidth() / 2.0f;
        centerY = layout2.getHeight() / 2.0f;
    }

    Rotate3dAnimation rotation;

    if (mIsFirstView == true) {
        layout1.setVisibility(View.GONE);
        layout2.setVisibility(View.VISIBLE);
        layout2.requestFocus();
        layout2.bringToFront();
        rotation = new Rotate3dAnimation( -90, 0, centerX, centerY, 200.0f, false);
    } else {
        layout2.setVisibility(View.GONE);
        layout1.setVisibility(View.VISIBLE);
        layout1.requestFocus();
        layout1.bringToFront();
        rotation = new Rotate3dAnimation(-90, 0, centerX, centerY, 200.0f, false);
        //rotation = new Flip3dAnimation(-90, 0, centerX, centerY);
    }

    rotation.setDuration(350);
    rotation.setFillAfter(true);
    rotation.setInterpolator(new LinearInterpolator());
    rotation.setAnimationListener(new AnimationListener() {

        public void onAnimationStart(Animation arg0) {

        }

        public void onAnimationRepeat(Animation arg0) {
            // TODO Auto-generated method stub

        }

        public void onAnimationEnd(Animation arg0) {
            WordDetailItemAdapter.notifyAdapter();
        }
    });
    if (mIsFirstView == true) {
        layout2.startAnimation(rotation);
    } else {
        layout1.startAnimation(rotation);
    }
}

}

1 Ответ

1 голос
/ 19 мая 2011

После ряда проб и ошибок я нашел решение своей проблемы.

В методе onCreate в конце я поставил следующие коды:

Handler tempHandler = new Handler() {
        public void handleMessage(Message msg) {

            wordDetailAdapter.notifyDataSetChanged();
        };
    };
    Message msg = tempHandler.obtainMessage();
    tempHandler.sendMessageDelayed(msg, 500);

Проблема заключалась в том, что при первом показе галереи на экране анимация переворота не работала Но, если я прокручиваю галерею, чтобы перейти другой пункт. После этого для каждого элемента работала анимация.

Решение сработало, но я не знаю, почему возникла проблема. Во-первых, проблема возникла не в версии 2.1, а в версии 2.2 и более поздних.

...