关于安卓viewpager空指针异常问题-问答-阿里云开发者社区-阿里云

开发者社区> 问答> 正文
阿里云
为了无法计算的价值
打开APP
阿里云APP内打开

关于安卓viewpager空指针异常问题

package com.sweetstar86.day6hw;

import android.app.Activity;
import android.content.Intent;
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.View;
import android.view.ViewGroup;

import java.util.ArrayList;

public class GuideActivity extends Activity implements ViewPager.OnPageChangeListener {

    private ViewPager viewPager;
    private ArrayList<View> views = new ArrayList<>();

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

    }

    public void initView() {
        views.add(getLayoutInflater().inflate(R.layout.layout_pre1, null));
        views.add(getLayoutInflater().inflate(R.layout.layout_pre2, null));


        viewPager.setOnPageChangeListener(this);
        viewPager.setAdapter(new MyPageAdapter());

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {


    }

    @Override
    public void onPageSelected(int position) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {

        if (state == views.size()) {
            Intent mainIntent = new Intent(GuideActivity.this, MainActivity.class);
            GuideActivity.this.startActivity(mainIntent);
            GuideActivity.this.finish();
        }
    }

    class MyPageAdapter extends PagerAdapter {

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

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View v = views.get(position);
            container.addView(v);
            return v;
        }

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

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

viewPager.setOnPageChangeListener(this);
initView();
处,报错。

展开
收起
爵霸 2016-03-05 15:27:38 2203 0
1 条回答
写回答
取消 提交回答
  • 爵霸

    viewPager没有初始化
    需要加上
    viewPager = (ViewPager)findViewById(R.id.xxxxxx);//viewpage的id找到对应的viewpage

    2019-07-17 18:53:38
    赞同 展开评论 打赏
问答排行榜
最热
最新
相关电子书
更多
From Java_Android to Swift iOS
立即下载
From Java/Android to Swift iOS
立即下载
低代码开发师(初级)实战教程
立即下载