如何在ViewPager中添加AnimationDrawable?

时间:2018-05-15 07:08:51

标签: android android-viewpager android-pageradapter animationdrawable

我正在尝试在ViewPager的第一页中添加AnimationDrawable。 我的想法是,每次进入第一页时,动画都将从最近的帧恢复。问题是当我从第三页翻到第一页时,或者当我从另一个活动回来时,它会先被卡住然后重新启动。

这是PagerAdapter类:

public class SignUpAdapter extends PagerAdapter implements Observer {

    private AVLoadingIndicatorView progressBar;
    private CallbackManager callbackManager;
    private LayoutInflater layoutInflater;
    private FloatingTextButton chatBtn;
    private LoginButton facebookBtn;
    private Context context;
    private TextView title_1;
    private TextView title_2;
    private ImageView image;
    private TextView text;
    private View view;
    private ImageView homeScreen;
    private AnimationDrawable anim;

    public SignUpAdapter(Context context, CallbackManager callbackManager) {
        this.context = context;
        this.callbackManager = callbackManager;
        ObservableObject.getInstance().addObserver(this);
    }

    public int[] slideImages = {
            0,
            R.drawable.chat_logo,
            R.drawable.headphone_logo
    };

    public String[] slideHeadings = {
            "",
            "Free Chat",
            "Supporting system"
    };


    @Override
    public Object instantiateItem(final ViewGroup container, int position) {
        layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
        view = layoutInflater.inflate(R.layout.sign_up_adapter, container, false);

        image = (ImageView) view.findViewById(R.id.slideImage);
        image.setImageResource(slideImages[position]);


        text = (TextView) view.findViewById(R.id.heading);
        text.setText(slideHeadings[position]);
        title_1 = (TextView) view.findViewById(R.id.title_1);
        title_2 = (TextView) view.findViewById(R.id.title_2);

        chatBtn = (FloatingTextButton) view.findViewById(R.id.ChatBtn);
        facebookBtn = (LoginButton) view.findViewById(R.id.facebookLoginBtn);
        facebookBtn.setReadPermissions("email", "public_profile");

        progressBar = (AVLoadingIndicatorView) view.findViewById(R.id.progressBar);
        progressBar.hide();
        Log.d("pos", String.valueOf(position));
        switch (position) {
            case 0:
                view.setBackgroundResource(R.drawable.change_screen);
                anim = (AnimationDrawable) view.getBackground();
                anim.setExitFadeDuration(2000);
                anim.stop();
                anim.start();
                setVisibility(View.VISIBLE, View.GONE, View.GONE);
                break;
            case 1:
                anim.stop();
                setVisibility(View.GONE, View.VISIBLE, View.GONE);
                chatBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        chatBtn.setEnabled(true);
                        logAnonymously();
                    }
                });
                break;
            case 2:
                setVisibility(View.GONE, View.GONE, View.VISIBLE);
                facebookBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        loginWithFaceBook();
                    }
                });
                break;
        }
        container.addView(view);
        return view;
    }


    @Override
    public int getCount() {
        return slideHeadings.length;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == (RelativeLayout) object;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((RelativeLayout) object);
    }

    public void logAnonymously() {
        FirebaseAuth mAuth = FirebaseAuth.getInstance();
        final Task<AuthResult> authResultTask = mAuth.signInAnonymously().addOnCompleteListener((Activity) context, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful())
                    startAnonymousActivity(view);
                else
                    Log.d("SignUpActivity", "error");
            }
        });
    }

    public void startAnonymousActivity(View view) {
        view.getContext().startActivity(new Intent(context, AnonymousUI.class));
        ((Activity) context).finish();
    }

    public void checkUserAuthorization() {
        Intent actionIntent = new Intent(Const.CHECK_USER_AUTHORIZATION);
        MyApp.context.sendBroadcast(actionIntent);
    }

    @Override
    public void update(Observable o, Object isAuthorized) {
        if ((boolean) isAuthorized) {
            progressBar.smoothToHide();
            context.startActivity(new Intent(context, LoginActivity.class));
            ((Activity) context).finish();
        } else {
            facebookBtn.setVisibility(View.VISIBLE);
            Toast.makeText(context, "you are not a registered user", Toast.LENGTH_SHORT).show();
        }
        ObservableObject.getInstance().deleteObserver(this);
    }

    public void loginWithFaceBook() {
        facebookBtn.registerCallback(this.callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                facebookBtn.setVisibility(View.GONE);
                AccessToken token = loginResult.getAccessToken();
                handleFacebookAccessToken(token);
            }

            @Override
            public void onCancel() {
            }

            @Override
            public void onError(FacebookException error) {
            }
        });
    }

    public void handleFacebookAccessToken(AccessToken token) {
        progressBar.show();
        AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
        FirebaseAuth.getInstance().signInWithCredential(credential)
                .addOnCompleteListener((Activity) context, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            checkUserAuthorization();
                        } else {
                            Toast.makeText(context, "facebook account not exist", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    public void setVisibility(int vis1, int vis2, int vis3) {
        title_1.setVisibility(vis1);
        title_2.setVisibility(vis1);
        chatBtn.setVisibility(vis2);
        facebookBtn.setVisibility(vis3);
    }


}

这是AnimationDrawebale XML文件:

<?xml version="1.0" encoding="UTF-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="false">


    <item android:drawable="@drawable/youth_6"
        android:duration="2000" />

    <item android:drawable="@drawable/youth_9"
        android:duration="2000" />

    <item android:drawable="@drawable/youth_11"
        android:duration="2000" />

    <item android:drawable="@drawable/youth_15"
        android:duration="2000" />

    <item android:drawable="@drawable/youth_4"
        android:duration="2000" />

    <item android:drawable="@drawable/youth_8"
        android:duration="2000" />


</animation-list>

1 个答案:

答案 0 :(得分:0)

您可以使用框架动画的处理程序。

声明

resNo = 0;全球范围内。如果要恢复或启动它,请调用startAnim()。

private void startAnim(){
  animHandler = new Handler();
  try {

      animHandler.post(runAnim);
  } catch (Exception e) {
      e.printStackTrace();
  }
}

并定义runAnim&gt;&gt;

 Runnable runAnim = new Runnable() {
    @Override
    public void run() {
        image.setBackgroundResource(res[resNo]);
        resNo++;
        if (resNo >= res.length) {
            resNo = 0;

        } else {
            if (animHandler != null)
                animHandler.postDelayed(this, 30);
        }
    }
};

当你想在

之后停止动画使用时
if (animHandler != null) {
        animHandler.removeCallbacks(runAnim);
    }