简体   繁体   中英

Change ImageView source in specific page in ViewPager Android

I want to change imageresource in specific page in view pager. This is what i've done.

This is onCreate activity ...

        ((PlaceholderFragment)mSectionsPagerAdapter.getItem(0)).updateImage(R.drawable.help1);
        ((PlaceholderFragment)mSectionsPagerAdapter.getItem(1)).updateImage(R.drawable.help2);
        ((PlaceholderFragment)mSectionsPagerAdapter.getItem(2)).updateImage(R.drawable.help3);
        ((PlaceholderFragment)mSectionsPagerAdapter.getItem(3)).updateImage(R.drawable.help4);

And this is the fragment class...

public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_help, container, false);
        ImageView imageView = (ImageView) rootView.findViewById(R.id.imageHelp);
        imageView.setImageResource(R.drawable.help4);
        return rootView;
    }

    public void updateImage(int image){
        ImageView imageView = (ImageView) getView().findViewById(R.id.imageHelp);
        imageView.setImageResource(image);

    }
}

But somehow it still give me error null pointer exception. How do I miss ? Thanks before and please help me :) Im stuck here for about 2 hours.

// declare rootView as global variable

public void updateImage(int image){
    ImageView imageView = (ImageView) rootView.findViewById(R.id.imageHelp);
    imageView.setImageResource(rootView);
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM