Android-анимация оставляет линии во время движения - PullRequest
4 голосов
/ 12 сентября 2011

У меня есть 12 установок ImageButtons в сетке 3x4 с использованием AbsoluteLayout. Когда пользователь нажимает на кнопку с изображением, оно увеличивается, чтобы заполнить экран, удерживает, а затем сжимается в исходное положение.

Анимация работает, за исключением того, что при уменьшении кнопки она иногда оставляет линии позади. (Я прикрепил изображения ниже).

Есть ли лучший способ добиться этой анимации? Что я могу сделать, чтобы предотвратить ошибки при рисовании, которые я получаю?

EDIT : Также линии исчезают, как только анимация заканчивается, они присутствуют только во время анимации.

Вот мой UDATED код анимации

private void animateCard(final CardButton c){
    this.isAnimating = true;
    CardPickerActivity.this.soundManager.playSound(c.name);
    Util.logD("Card:" + c.name + " clicked!");

    final int growDuration = 750;
    final int holdDuration = 500;
    final int shrinkDuration = 500;

    c.bringToFront();
    AnimationSet asGrow = new AnimationSet(true);
    float newScale = 2.0f;
    float newX = (CardPickerActivity.this.wDesk/2.0f - CardPickerActivity.this.cardSize/2.0f*newScale - c.getLeft())/newScale;
    float newY = (CardPickerActivity.this.hDesk/2.0f - CardPickerActivity.this.cardSize/2.0f*newScale - c.getTop() )/newScale;
    TranslateAnimation taG = new TranslateAnimation(0.0f, newX , 0.0f, newY);
    ScaleAnimation saG = new ScaleAnimation(    1.0f, newScale, 1.0f, newScale);

    taG.setRepeatCount(1);
    saG.setRepeatCount(1);
    taG.setRepeatMode(Animation.REVERSE);
    saG.setRepeatMode(Animation.REVERSE);

    asGrow.addAnimation(taG);
    asGrow.addAnimation(saG);
    asGrow.setDuration(growDuration);


    c.startAnimation(asGrow);

}

Вот XML-макет для действия, не обращайте внимания на layout_x и layout_y, которые я установил позже на основе экрана устройства:

<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/cardLayout" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <com.myProject.CardButton
        android:id="@+id/btn1" android:text="1" android:layout_x="0px"
        android:layout_y="0px" android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <com.myProject.CardButton
        android:id="@+id/btn2" android:text="2" android:layout_x="10px"
        android:layout_y="10px" android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <com.myProject.CardButton
        android:id="@+id/btn3" android:text="3" android:layout_x="20px"
        android:layout_y="20px" android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <com.myProject.CardButton
        android:id="@+id/btn4" android:text="4" android:layout_x="30px"
        android:layout_y="30px" android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <com.myProject.CardButton
        android:id="@+id/btn5" android:text="5" android:layout_x="40px"
        android:layout_y="40px" android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <com.myProject.CardButton
        android:id="@+id/btn6" android:text="6" android:layout_x="40px"
        android:layout_y="40px" android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <com.myProject.CardButton
        android:id="@+id/btn7" android:text="7" android:layout_x="40px"
        android:layout_y="40px" android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <com.myProject.CardButton
        android:id="@+id/btn8" android:text="8" android:layout_x="40px"
        android:layout_y="40px" android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <com.myProject.CardButton
        android:id="@+id/btn9" android:text="9" android:layout_x="40px"
        android:layout_y="40px" android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <com.myProject.CardButton
        android:id="@+id/btn10" android:text="10" android:layout_x="40px"
        android:layout_y="40px" android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <com.myProject.CardButton
        android:id="@+id/btn11" android:text="11" android:layout_x="40px"
        android:layout_y="40px" android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <com.myProject.CardButton
        android:id="@+id/btn12" android:text="12" android:layout_x="40px"
        android:layout_y="40px" android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</AbsoluteLayout>

Вот класс CardButton, по сути, ImageButton с еще несколькими переменными-членами

public class CardButton extends ImageButton {
    public CardButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
    public CardButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public CardButton(Context context) {
        super(context);
    }

    public String name;
    public Bitmap image;

    public int soundRes;
    public int imageRes;

    public String customImagePath;
    public String customSoundPath;
}

Here is what the grid looks like before touch

Here is what the grid looks like when a button has finished growing

Here is what the grid looks like when the button has finished skrinking. Notice the white vertical lines

Ответы [ 3 ]

2 голосов
/ 19 сентября 2011

Так что я решил проблему, но не так, как я доволен.

Сначала в месте, где я не показывал код, я звонил:

cardButton.setBackgroundColor(Color.WHITE);

Если я закомментировал эту строку, проблема исчезла.Это однако произвело CardButtons, которые были похожи на стандартные кнопки Android.Я не хотел, чтобы они выглядели, поэтому я попытался установить белую кнопку «стиль» несколькими другими способами.Все это привело к ошибке.

В попытке лучше понять, что происходит, и выследить возможную ошибку в Android или в моем коде, я создал тестовый проект, который включал только одно действие с сеткой 3x4 и ничего больше.Этот тестовый проект содержал одно действие и один файл XML.Начав с базовой сетки, я не смог воспроизвести ошибку, затем я начал добавлять все больше и больше функций в тестовое приложение и в итоге воссоздал исходную активность, но без ошибки.

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

Теперь у меня есть два вида деятельности, которые используют идентичный код в разных проектах Android.Один из них является единственным видом деятельности в проекте, тогда как другой является частью более крупного проекта со многими видами деятельности.Версия в более крупном проекте содержит ошибку, а версия в отдельном проекте - нет.Я не уверен, как это интерпретировать, и я был бы очень признателен за любые отзывы / комментарии по этому поводу.

Так что, пока я не могу понять, почему я получаю ошибку рисования в контексте моего более крупного приложения, ясобираюсь использовать стоковый фон кнопки андроида.

Обновление : по прихоти я сделал фон 9Patch, который был белым.Это решило проблему.

1 голос
/ 17 сентября 2011

Улучшение / возможное решение:

У меня есть улучшения в вашем коде, надеюсь, это исправит и вашу проблему обновления. Также почувствуйте, что это правильный способ делать то, что вы пытаетесь.

growShrink.addAnimation(ta);
growShrink.addAnimation(sa);
holdAnim.setStartOffset(growDuration); // hold will start when grow stops.
growShrink.addAnimation(holdAnim);

growShrink.setRepeatCount(1);
growShrink.setRepeatMode(Animation.REVERSE);
growShrink.setInterpolator(new LinearInterpolator());

Это будет воспроизводить растущую анимацию в обратном направлении. Не требуется анимация и слушатель конца для запуска анимации удержания и сжатия.


Альтернативный раствор:

Добавьте все свои растущие, удерживающие и уменьшающие анимации к одному AnimtaionSet. Установите начальные смещения удержания и сжатия анимации соответствующим образом.

// growAnim will start at 0.
holdAnim.setStartOffset(growDuration); 
shrinkAnim.setStartOffset(growDuration+holdDuration);
1 голос
/ 16 сентября 2011

Это может быть причиной проблемы.Иногда анимация onAnimationEnd срабатывает немного до того, как закончится настоящая анимация.

Вы можете создать пользовательский вид или макет и переопределить его метод animationEnd и добавить интерфейс, чтобы вы могли настроить прослушиватель.

Вот пример

Класс CustomLayout

public class CustomLayout extends LinearLayout {
    private LayoutAnimationListener mListner;

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

    public CustomLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onAnimationEnd() {
        super.onAnimationEnd();
        if(mListner != null){
            mListner.onAnimationEnd(CustomLayout.this);
        }
    }

    @Override
    protected void onAnimationStart() {
        super.onAnimationStart();
        if(mListner != null){
            mListner.onAnimationStart(CustomLayout.this);
        }
    }

    public static interface LayoutAnimationListener {
        //Notifies the start of the animation.
        void onAnimationStart(CustomLayout cLayout);
        //Notifies the end of the animation.
        void onAnimationEnd(CustomLayout cLayout);
    }

    public void setLayoutAnimationListener(LayoutAnimationListener listener){
        mListner = listener;
    }
}

Таким образом, в своей деятельности вы можете использовать его в качестве обычного линейного макета и вместо добавления слушателя анимации к анимации, вы можете добавить его в макет, например

com.blessan.CustomLayout layout   = 
            (com.blessan.CustomLayout)findViewById(R.id.counts_layout);
    LayoutAnimationListener layoutAnimListener = new LayoutAnimationListener() {           
        @Override
        public void onAnimationStart(CustomLayout cLayout) {

        }

        @Override
        public void onAnimationEnd(CustomLayout cLayout) {

        }

    };
    layout.setLayoutAnimationListener(layoutAnimListener);

Этоможет работать на тебя.Попробуйте.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...