我使用此autoscroll viewpager library和PagerAdapter来显示图像和文本。然后我使用动画将文本从左侧移动到右侧。问题是viewpager的每个页面都没有出现动画。 如何为每个页面设置文本动画?
public class MainActivity extends AppCompatActivity {
ArrayList<ModelObject> arrayList = new ArrayList<>();
String[] country = new String[] { "China", "India", "United States",
"Indonesia", "Brazil", "Pakistan", "Nigeria"};
int[] flag = new int[] { R.drawable.china, R.drawable.india,
R.drawable.unitedstates, R.drawable.indonesia,
R.drawable.brazil, R.drawable.pakistan, R.drawable.nigeria};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
ViewPagerAdapter swipeAdapter = new ViewPagerAdapter(this, country, flag);
viewPager.setAdapter(swipeAdapter);
viewPager.setPageTransformer(false, new ViewPager.PageTransformer() {
@Override
public void transformPage(View page, float position) {
final float normalizedposition = Math.abs(Math.abs(position) - 1);
page.setAlpha(normalizedposition);
}
});
}
public class ViewPagerAdapter extends PagerAdapter {
// Declare Variables
Context context;
String[] country;
int[] flag;
LayoutInflater inflater;
public ViewPagerAdapter(Context context, String[] country, int[] flag) {
this.context = context;
this.country = country;
this.flag = flag;
}
@Override
public int getCount() {
return flag.length;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == ((RelativeLayout) object);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
// Declare Variables
TextView txtcountry;
ImageView imgflag;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.pagefrag, container, false);
// Locate the TextViews in viewpager_item.xml
txtcountry = (TextView) itemView.findViewById(R.id.country);
// Capture position and set to the TextViews
txtcountry.setText(country[position]);
txtcountry.startAnimation(AnimationUtils.loadAnimation(context, R.anim.myanim));
// Locate the ImageView in viewpager_item.xml
imgflag = (ImageView) itemView.findViewById(R.id.flag);
// Capture position and set to the ImageView
imgflag.setImageResource(flag[position]);
// Add viewpager_item.xml to ViewPager
((ViewPager) container).addView(itemView);
return itemView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
// Remove viewpager_item.xml from ViewPager
((ViewPager) container).removeView((RelativeLayout) object);
}
}
}
答案 0 :(得分:0)
您可以使用ViewPager.PageTransformer
界面为页面内的视图设置动画
class MyPageTransformer implements ViewPager.PageTransformer {
@Override
public void transformPage(View page, float position) {
float pageTimesPosition = page.getWidth() * position;
View text = page.findViewById(R.id.text);
if (text != null) {
text.setAlpha(1.0f - position);
}
}
}
然后用viewPager.setPageTransformer(false, new MyPageTransformer());
设置Transformer