设置按钮可见性时出现空指针异常

时间:2014-11-03 19:42:02

标签: java android nullpointerexception

我要改变viewpager上其中一个按钮的可见性,但是我在这一行上得到了一个N​​ull Pointer Exception:

save_button.setVisibility(Button.INVISIBLE);

我想知道为什么会这样?是因为我没有在我的InstantiateItem()中获取按钮的可见性属性吗?我是不是该?如果是这样,如果用户查看页面,如何根据事实更改按钮可见性?

我要做的是:如果在viewpager中查看了所有视图,则显示“保存”按钮。如果未查看所有视图,则隐藏保存按钮。

这是我的代码:

boolean isViewed = false;
boolean buttonState= false; //unpressed, if true == pressed
int buttonValue = 0;

//Methods
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.score_viewpager);

    //Specify the number of pages/views
    numberOfPages = new Integer[]{1, 2, 3, 4, 5};

    final Button save_button = (Button) findViewById(R.id.save);

    //Initialize adapter to populate view
    myAdapter = new MyAdapter(ScoreCollectionPager.this, numberOfPages, save_button);

    //Search view for viewpager Id and set the adapter on the first item
    viewPager = (ViewPager) findViewById(R.id.viewPager);
    viewPager.setAdapter(myAdapter);
    viewPager.setCurrentItem(0);

    //Attach the page change listener inside the activity
    viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        Button save_button = (Button) findViewById(R.id.save);

        // This method will be invoked when the current page is scrolled
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        //This method will be invoked when a new page becomes selected
        @Override
        public void onPageSelected(int position) {
            //get position
            isViewed = true;

            if (isViewed  && (position == numberOfPages.length)) {

                save_button.setVisibility(Button.VISIBLE);
            }
            else {
                save_button.setVisibility(Button.INVISIBLE); // Null Pointer Exception here? why?
            }

        }

        // Called when the scroll state changes:
        // SCROLL_STATE_IDLE, SCROLL_STATE_DRAGGING, SCROLL_STATE_SETTLING
        @Override
        public void onPageScrollStateChanged(int i) {
            //get state
        }
    });

}

private class MyAdapter extends PagerAdapter {

    //fields
    Button save_button;

    //Constructor
    public MyAdapter(Context context, numberOfPages, Button save_button) {

        this.context = context;
        this.numberOfPages = new ArrayList<Integer>(Arrays.asList(numberOfPages));
        this.save_button = save_button;

    }

    //Returns total number of pages
    @Override
    public int getCount() {
        return numberOfPages.size();
    }

    /**
     * Create the page for the given position.
     *
     * @param parent The containing View in which the page will be shown.
     * @param position  The page position to be instantiated.
     *
     * @return Returns an Object representing the new page. This does not need
     *         to be a View, but can be some other container of the page.
     */
    @Override
    public Object instantiateItem(ViewGroup parent, final int position) {

        //Get the inflater
        LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        //inflate the root layout
        View view = inflater.inflate(R.layout.score_collection, null);

        //Save Button
        save_button = (Button) view.findViewById(R.id.save);

        save_button.setOnClickListener(new ViewGroup.OnClickListener() {
            public void onClick(View view) {

                //code for saving

        }});
    }
}

3 个答案:

答案 0 :(得分:2)

将下面的代码移到onPageSelected方法

 Button save_button = (Button) findViewById(R.id.save);

答案 1 :(得分:1)

我可以看到Button实例不一样。确保在同一布局中获得相同的对象。代码中的前2个按钮属于布局R.layout.score_viewpager,最后一个属于R.layout.score_collection(在MyAdapter中)。

答案 2 :(得分:0)

行。这是一个烂摊子,但如果你在onCreate中为类变量赋值,你可以在其他内部类中访问它,而不必多次调用findViewById(昂贵的调用)。

类var:

private final Button saveButton;

在onCreate中设置值:

saveButton = (Button) findViewById(R.id.save);