例子布局文件:
主activity布局文件:activity_view_pager.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ViewPagerActivity">
<android.support.v4.view.ViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:overScrollMode="never"
>
</android.support.v4.view.ViewPager> </android.support.constraint.ConstraintLayout> viewpager子项布局文件:layout_viewpager.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/image_view"
android:layout_width="match_parent"
android:layout_height="match_parent" /> </LinearLayout>
例子源代码:
package com.example.viewpager; import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView; import java.util.ArrayList;
import java.util.List; public class ViewPagerActivity extends AppCompatActivity {
ViewPager viewpager; List<View> listview ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_pager);
viewpager = findViewById(R.id.view_pager); listview = new ArrayList<>();
for(int i=0;i<3;i++){ View view = LayoutInflater.from(this).inflate(R.layout.layout_viewpager,null);
ImageView imageView= view.findViewById(R.id.image_view); switch(i){
case 0:
imageView.setBackgroundColor(Color.RED);
break;
case 1:
imageView.setBackgroundColor(Color.GREEN);
break;
case 2:
imageView.setBackgroundColor(Color.BLUE);
break; }
listview.add(view); }
viewpager.setAdapter(new PagerAdapter() {
@Override
public int getCount() {
return listview.size();
} @Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
return view == o;
// return false;
} @NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
container.addView(listview.get(position));
return listview.get(position);
// return super.instantiateItem(container, position);
} @Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
// super.destroyItem(container, position, object);
container.removeView(listview.get(position));
}
}); }
}