2 sinat 33645256 sinat_33645256 于 2016.03.26 20:31 提问

安卓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();
处,报错。

3个回答

danielinbiti
danielinbiti   Ds   Rxr 2016.03.26 20:48
已采纳
 viewPager没有初始化
 需要加上
 viewPager =   (ViewPager)findViewById(R.id.xxxxxx);//viewpage的id找到对应的viewpage
qq_26971803
qq_26971803   2016.03.26 20:52

报空指针的时候应该第一时间检查一下是否实例化图片说明

qq_33552256
qq_33552256 回复sweetstar86: 混几个积分,混几个积分,混几个积分,混几个积分,谢谢
一年多之前 回复
sinat_33645256
sinat_33645256 谢谢,我记住了~
一年多之前 回复
cyxevil
cyxevil   2016.03.28 11:14

viewPager = (ViewPager)findViewById(R.id.xxxxxx);

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!