Android ViewPager和PagerAdapter简单代码写法

Android ViewPager和PagerAdapter简单代码写法


总是忘记,记下来备忘:

package zhangphil.test;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
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 android.widget.ImageView;

import java.util.ArrayList;

public class ViewPagerActivity extends AppCompatActivity {
    private ArrayList images = new ArrayList<>();

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

        for (int i = 0; i < 5; i++) {
            ImageView imageView = new ImageView(getApplicationContext());
            imageView.setImageResource(R.mipmap.ic_launcher);
            images.add(imageView);
        }

        ViewPager viewPager = findViewById(R.id.view_pager);
        viewPager.setAdapter(new VPAdapter());
    }

    private class VPAdapter extends PagerAdapter {

        @Override
        public View instantiateItem(ViewGroup container, int position) {
            container.addView(images.get(position));
            return images.get(position);
        }

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

        @Override
        public int getCount() {
            return images.size();
        }

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

你可能感兴趣的:(Android)