简单实现图片间的切换动画 主要用到ViewPager
简单实现图片间的切换动画 主要用到ViewPager
ViewPager是android扩展包v4包中的类,这个类可以让用户左右切换当前的view。
ViewPager类需要一个PagerAdapter适配器类给它提供数据
PagerAdapter适配器,必须实现四个方法getCount、isViewFromObject、destroyItem、instantiateItem
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
import uk.co.senab.photoview.PhotoView;
public class ViewPagerActivity extends AppCompatActivity {
private ViewPager vp; //Lay_out中设置了ViewPager
private List<PhotoView> myDate; //泛型,存放相同数据类型
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_pager);
vp = (ViewPager) findViewById(R.id.vp);
myDate = new ArrayList<>();
PhotoView img = new PhotoView(this);
img.setImageResource(R.mipmap.image1); //获得图片
myDate.add(img);
img = new PhotoView(this);
img.setImageResource(R.mipmap.image2);
myDate.add(img);
img = new PhotoView(this);
img.setImageResource(R.mipmap.image3);
myDate.add(img);
img = new PhotoView(this);
img.setImageResource(R.mipmap.image4);
myDate.add(img);
vp.setAdapter(new MyViewPagerAdapter(myDate));
}
public class MyViewPagerAdapter extends PagerAdapter {
private List<PhotoView> myDate;
public MyViewPagerAdapter(List<PhotoView> myDate) {
this.myDate = myDate;
}
@Override
public int getCount() {
return myDate.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
container.addView(myDate.get(position));
return myDate.get(position);
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView(myDate.get(position));
}
}
}
Lay_out:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.administrator.jreduch05.ViewPagerActivity">
<android.support.v4.view.ViewPager //用于显示左右滑动的界面
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#1b1a1a"
android:id="@+id/vp">
</android.support.v4.view.ViewPager>
</RelativeLayout>