Android:如何在ViewPager中设置文本动画

时间:2016-03-27 19:52:36

标签: java android animation android-viewpager fragment

当用户滑动到下一个屏幕时,我想开始淡入动画,但我无法让它正常工作。问题是动画在第一和第二屏幕上同时开始,在第三和第四屏幕等。

这是我的PageFragment;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    Animation in;
    Animation out;

    in = new AlphaAnimation(0.0f, 1.0f);
    in.setDuration(2000);

    out = new AlphaAnimation(1.0f, 0.0f);
    out.setDuration(2000);

    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.page_fragment_layout,container,false);
    textView = (TextView)view.findViewById(R.id.textView);
    Bundle bundle = getArguments();
    String message = bundle.getString("count");
    textView.setText(message);
    textView.setAnimation(in);
    return view;
}}

SwipeAdapter

public class SwipeAdapter extends FragmentStatePagerAdapter{
public SwipeAdapter(FragmentManager fm) {
    super(fm);
}

@Override
public Fragment getItem(int i) {
    String[] historia = {"1", "2", "3", "4", "5"};
    Fragment fragment = new PageFragment();
    Bundle bundle = new Bundle();
    bundle.putString("count", historia[i]);
    fragment.setArguments(bundle);
    return fragment;
}

@Override
public int getCount() {
    return 5;
}}

MainActivity

public class MainActivity extends FragmentActivity {
ViewPager viewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    viewPager = (ViewPager) findViewById(R.id.view_pager);
    SwipeAdapter swipeAdapter = new SwipeAdapter(getSupportFragmentManager());
    viewPager.setAdapter(swipeAdapter);

}}

感谢任何有用的答案! :)

1 个答案:

答案 0 :(得分:0)

使用ViewPager.OnPageChangeListener注册swipeAdapter(如swipeAdapter.addOnPageChangeListener()中所述)。然后,您可以将动画内容移动到public void onPageSelected(int position)。别忘了在onResume/onPause

中调用那些添加/删除侦听器